你不必这样做。事实上,你不应该因为你可以让你的对象处于不一致的状态。假设您有:
public class Category {
public Int32 Id { get; set; }
}
public class SomeClass {
public Int32 Id { get; set; }
public virtual Category Category { get; set; }
}
这是有效的。您只需告知EF在其配置中如何找到外键。根据上述内容,它会尝试使用SomeClass.Category_Id
,但您可以随意更改它。
编辑:如果你想改变外键,你可以通过添加配置类和OnModelCreating
事件过程中添加它这样做的:
internal class ForSomeClassEntities : EntityTypeConfiguration<SomeClass> {
public ForSomeClassEntities(String schemaName) {
this.HasRequired(e => e.Category)
.WithMany()
.Map(map => map.MapKey("CategoryId"));
this.ToTable("SomeClass", schemaName);
}
}
在你重写Context
类:
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
base.OnModelCreating(modelBuilder);
modelBuilder.Configurations
.Add(new ForSomeClassEntities("SomeSchema"))
;
}
使用上面相同的类会告诉EF寻找名为SomeClass.CategoryId
的外键属性。
你不需要两个:http://stackoverflow.com/a/5282275/270591+在答案的末尾的链接。两个链接更多:http://stackoverflow.com/questions/4703378/ef4-independent-associations-why-avoid-them和http://stackoverflow.com/questions/9253234/what-is-the-point-of-创建外键关键属性当使用实体框架 – Slauma 2012-08-08 15:20:20
@Slauma,谢谢你的额外信息。这真的有助于澄清一些 - 我没有意识到这些是不同类型的关联。如果您将其作为答案张贴,我想接受它。 – ametren 2012-08-08 17:07:00
你应该接受@ Yuck的回答。他非常清楚地解释说,你*可以在没有FK属性的情况下工作,举例和一切,这是你的问题,他回答了。我只对“你不应该”使用FK属性有一点否决权。但这更像是一场有争议的辩论。你会发现人们说“你应该”的同样经常的答案。 – Slauma 2012-08-08 18:35:40