问题
I'm trying to do a one-to-many relationship in Entity Framework where one of the many items is optionally designated as default.
public class SomeEntity
{
public int Id { get; set; }
public Item DefaultItem { get; set; } // Optional
public ICollection<Item> Items { get; set; }
}
public class Item
{
public int Id { get; set; }
public string ItemName { get; set; }
public SomeEntity SomeEntity { get; set; }
}
The configuration for the one-to-many in fluent API seems pretty straightforward:
HasMany(e => e.Items).WithRequired(i => i.SomeEntity).WillCascadeOnDelete(true);
But the solution for implementing the default item has proven elusive. I tried this (and various variations) with no luck. It tells me that 'Schema specified is not valid'.
HasOptional(e => e.DefaultItem).WithRequired(i => i.SomeEntity);
Any ideas? Thanks in advance.
回答1:
That is a bit untypical 'setup' (and it's usually designated via some 'flag' on the item - but I can possibly see a need for something similar), and relating one item to the same parent twice.
However, this should work...
modelBuilder.Entity<SomeEntity>()
.HasOptional(x => x.DefaultItem)
.WithOptionalPrincipal() // x => x.DefaultForEntity)
.WillCascadeOnDelete(false);
...
// public SomeEntity DefaultForEntity { get; set; } // optional
...and use it like:
var item = new Item { ItemName = "Default1", };
db.SomeEntities.Add(new SomeEntity { DefaultItem = item, Items = new[]
{
item,
new Item{ ItemName = "Item1", },
new Item{ ItemName = "Item2", },
new Item{ ItemName = "Item3", },
new Item{ ItemName = "Item4", },
}
});
db.SaveChanges();
来源:https://stackoverflow.com/questions/15751798/entity-framework-one-to-many-with-default