Entity Framework One-to-Many with Default

独自空忆成欢 提交于 2019-12-18 07:13:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!