Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

c# - Entity Framework One-to-Many with Default

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...