实体框架1对许多具有默认

实体框架1对许多具有默认

问题描述:

我试图做实体框架一个一对多的关系,其中的许多项目中的一个可选指定为默认值。

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; }
}

有关的配置单对多用流利的API看起来很简单

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.

这是一个有点非典型的设置(和它的通过该项目的一些'标志'通常指定 - 但我可以看到可能需要类似的东西),以及与一个项目到同一母公司的两倍。

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