[英]How to properly create an EF One-to-Zero-or-One relationship with navigation properties on both ends?
In my model I have two objects: Lead
and Work
. 在我的模型中,我有两个对象:
Lead
和Work
。 Lead
may have a related Work
, but Work
must have a related Lead
. Lead
可能有相关的Work
,但是Work
必须有相关的Lead
。 How do I properly express this using EF Code First and Fluent API? 如何使用EF Code First和Fluent API正确表达这一点? I've spent most of the day so far going in circles trying to do this, but I'm getting nowhere.
到目前为止,我大部分时间都花在圈子里,试图做到这一点,但我一无所获。 The problem (maybe?), is that I need to have the navigation properties on both sides of the relationship.
问题(也许是?)是,我需要在关系的两边都具有导航属性。 Here's how I've got my objects configured so far:
到目前为止,这是我配置对象的方式:
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);
Attempting to reverse engineer a test database yields a One-to-Many relationship, which is not what I want. 尝试对测试数据库进行反向工程会产生一对多关系,这不是我想要的。 I'd appreciate suggestions on how to properly configure the relationship.
我将对有关如何正确配置关系的建议表示赞赏。
If lead is a principal (Lead must exist first), the classes could look like this. 如果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; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.