我有两个来自同一个表的外键,如下所示:
public class OfferTemplate { ...
[ForeignKey("CompanyAgentBuyer_CompanyAgentID")]
[InverseProperty("OfferTemplatesAsBuyer")]
public virtual CompanyAgent CompanyAgentBuyer { get; set; }
[ForeignKey("CompanyAgentBroker_CompanyAgentID")]
[InverseProperty("OfferTemplatesAsBroker")]
public virtual CompanyAgent CompanyAgentBroker { get; set; }
public int CompanyAgentBuyer_CompanyAgentID { get; set; }
public int? CompanyAgentBroker_CompanyAgentID { get; set; }
...
}
在模型上我得到了这个设置:
modelBuilder.Entity<OfferTemplate>()
.HasRequired(ca => ca.CompanyAgentBuyer)
.WithMany(t => t.OfferTemplatesAsBuyer)
.HasForeignKey(ca => ca.CompanyAgentBuyer_CompanyAgentID)
.WillCascadeOnDelete(false);
modelBuilder.Entity<OfferTemplate>()
.HasOptional(ca => ca.CompanyAgentBroker)
.WithMany(t => t.OfferTemplatesAsBroker)
.HasForeignKey(ca => ca.CompanyAgentBroker_CompanyAgentID)
.WillCascadeOnDelete(false);
到目前为止一切正常,除非我进行查询:
var templates = from user in context.UsersInformation
from cTemplate in context.OfferTemplates
where user.User.Equals(userID) && cTemplate.Company == user.Company
select cTemplate;
var x = templates.FirstOrDefault().CompanyAgentBuyer;
正在正确填充ID属性(CompanyAgentBuyer_CompanyAgentID&amp; CompanyAgentBroker_CompanyAgentID)时,未填充实例(如本例中的x)。我尝试使用Include方法,但它也没有用。我缺少什么想法?
答案 0 :(得分:0)
我最终将模型更改为:
modelBuilder.Entity<CompanyAgent>()
.HasMany(e => e.OfferTemplatesAsBroker)
.WithOptional(e => e.CompanyAgentBroker)
.HasForeignKey(e => e.CompanyAgentBroker_CompanyAgentID);
modelBuilder.Entity<CompanyAgent>()
.HasMany(e => e.OfferTemplatesAsBuyer)
.WithRequired(e => e.CompanyAgentBuyer)
.HasForeignKey(e => e.CompanyAgentBuyer_CompanyAgentID)
.WillCascadeOnDelete(false);
现在它正在运作。