我有以下类定义
public abstract class AbstractClass
{
[Key]
public string Name { get; set; }
public virtual IndependentClass IndependentClass { get; set; }
public string IndependentClassName { get { return IndependentClass == null ? "<NULL>" : IndependentClass.Name; } }
}
public class Impl1 : AbstractClass
{
}
public class Impl2 : AbstractClass
{
}
public class IndependentClass
{
[Key]
public string Name { get; set; }
public virtual Impl1 Impl1 { get; set; }
public virtual ICollection<Impl2> Impl2s { get; set; }
}
这些在我的Context.OnModelCreating
:
modelBuilder.Entity<AbstractClass>().HasOptional(abs => abs.IndependentClass);
modelBuilder.Entity<IndependentClass>().HasRequired(ind => ind.Impl1);
modelBuilder.Entity<IndependentClass>().HasMany(ind => ind.Impl2s);
我的初始化看起来像这样(将数组添加到上下文并context.SaveChanges()
修剪)
var impl1s = new[]
{
new Impl1() { Name = "a" },
new Impl1() { Name = "b" },
new Impl1() { Name = "c" }
}
var inds = new[]
{
new IndependentClass() { Name = "A", Impl1 = impl1s[0] },
new IndependentClass() { Name = "B", Impl1 = impl1s[1] }
}
var impl2s = new[]
{
new Impl2() { Name = "a1", IndependentClass = inds[0] },
new Impl2() { Name = "a2", IndependentClass = inds[0] },
new Impl2() { Name = "b1", IndependentClass = inds[1] },
new Impl2() { Name = "b2", IndependentClass = inds[1] },
new Impl2() { Name = "c1", IndependentClass = null }
}
最后,我有一个简单的视图,可以转储每个数据库集合。我的问题是导航属性没有像我需要的那样填充。即,我的观点的输出是这样的:
Independent Classes:
A: Impl1 = a, Impl2s = []
B: Impl1 = b, Impl2s = []
Impl1s
a: IndependentClass = <NULL>
b: IndependentClass = <NULL>
c: IndependentClass = <NULL>
Impl2s
a1: IndependentClass = A
a2: IndependentClass = A
b1: IndependentClass = B
b2: IndependentClass = B
c1: IndependentClass = <NULL>
IndepdendentClass 应该填充它们的 Impl2,前两个 Impl1 应该填充 IndependentClass。
谁能告诉我我做错了什么?