我有以下两个Entitites和相应的EntityTypeConfigurations
public class Master
{
public int Id { get; set; }
public int RequestId { get; set; }
public string ClientNo { get; set; }
public string SomeValue { get; set; }
public ICollection<Child> Childs { get; set; }
}
public class MasterConfig : EntityTypeConfiguration<Master>
{
public MasterConfig()
{
ToTable("Master", "MySchema");
HasKey(k => k.Id);
HasMany(m => m.Childs)...
// Connect Master.RequestId to Child.RequestId
// and Master.ClientNo to Child.ClientNo
}
}
public class Child
{
public int Id { get; set; }
public int RequestId { get; set; }
public string ClientNo { get; set; }
public string SomeOtherValue { get; set; }
}
public class ChildConfig : EntityTypeConfiguration<Child>
{
public ChildConfig()
{
ToTable("Child", "MySchema");
HasKey(k => k.Id);
}
}
我想按照我的方式进行配置
myAppContext.Masters.Include(m => m.Childs).First(m => m.Id == 4);
它将加载ID为4的所有Master和相应的maching Childs。 不知怎的,我无法使它发挥作用。
答案 0 :(得分:1)
关系基于 FK 到 PK 。在您的方案中,RequestId
不是Master
或Child
的主键。您应该拥有Request
模型,其RequsetId
为 PK ,并且应具有Master
的导航属性,并且Child
模型不应直接绑定到Request
,它应该绑定到Master
。您的模型应如下所示:
public class Request
{
public int Id { get; set; }
public string ClientNo { get; set; }
public virtual ICollection<Master> MasterCollection { get; set; }
}
public class RequestMap : EntityTypeConfiguration<Request>
{
HasKey(m => m.Id);
}
public class Master
{
// Id is same as RequestId
public int Id { get; set; }
public int RequestId { get; set; }
public string SomeValue { get; set; }
public virtual Request Request { get; set; }
public virtual ICollection<Child> Childs { get; set; }
}
public class MasterConfig : EntityTypeConfiguration<Master>
{
public MasterConfig()
{
ToTable("Master", "MySchema");
HasKey(k => k.Id);
// Map Request and Master
HasRequired(m => m.Request)
.WithMany(m => m.MasterCollection)
.HasForeignKey(m => m.RequestId);
}
}
public class Child
{
public int Id { get; set; }
public string SomeOtherValue { get; set; }
public int MasterId { get; set; }
public virtual Master Master { get; set; }
}
public class ChildConfig : EntityTypeConfiguration<Child>
{
public ChildConfig()
{
ToTable("Child", "MySchema");
HasKey(k => k.Id);
HasRequired(m => m.Master)
.WithMany(m => m.Childs)
.HasForeignKey(m => m.MasterId);
}
}
通过更改您的模型以适应这种情况,现在您可以根据需要加载Master
和相关的Childs
:
Master master = myAppContext.Masters
.Include(m => m.Childs)
.First(m => m.Id == 4);
如果您想根据Master加载Request
数据:
Master master = myAppContext.Masters
.Include(m => m.Request)
.Include(m => m.Childs)
.First(m => m.Id == 4);
您还可以为任何孩子加载Master
和Request
个详细信息:
Child child = myAppContext.Childs
.Include(m => m.Master.Request)
.First(m => m.Id == 2);