在我的模型中,我有两个对象:Lead
和Work
。 Lead
可能有相关的Work
,但Work
必须有相关的Lead
。如何使用EF Code First和Fluent API正确表达这一点?到目前为止,我大部分时间都在试图这样做,但我无处可去。问题(可能?),是我需要在关系的两边都有导航属性。以下是我到目前为止配置对象的方法:
public class Lead {
public int Id { get; set; }
public int? WorkId { get; set; }
public virtual Work Work { get; set; }
}
public class Work {
public int Id { get; set; }
//public int LeadId { get; set; } <- I think this is necessary?
public virtual Lead Lead { get; set; }
}
// this seems to make a one-to-one relationship, but it's setting
// the column references as the Id columns on both sides, so it's wrong...
// Also causes this exception:
// A dependent property in a ReferentialConstraint is mapped to a store-generated column. Column: 'Id'.
this.HasOptional(t => t.Work).WithRequired(t => t.Lead);
尝试对测试数据库进行反向工程会产生一对多的关系,这不是我想要的。我很欣赏有关如何正确配置关系的建议。
答案 0 :(得分:0)
如果lead是一个主体(Lead必须首先存在),那么这些类可能看起来像这样。
public class Lead {
public int Id { get; set; }
public virtual Work Work { get; set; }
}
public class Work {
[Key, ForeignKey("Lead")]
public int Id { get; set; }
public virtual Lead Lead { get; set; }
}