如何摆脱 EF 中的外键属性?
我使用 EF CTP 5 Code First。如果您要求 EF 为这样的模型生成数据库,它将为您创建适当的外键关系:
public class Parent
{
public ICollection<Child> MyChildren { get; set; }
}
public class Child
{
public Parent MyParent { get; set; }
}
作为此类生成的结果,子表将具有类似 MyParent_Id 字段的内容。现在我遇到了相反的问题 - 我有一个数据库模式,我必须为其构建类似的简单模型。我所说的类似简单是指没有任何显式的外键属性。有什么办法可以做到吗?
我发现进行映射的唯一方法看起来像这样,但它意味着在我试图避免的模型中具有公共属性 MyParentId 。那么如何避免呢?
public class Child
{
[Column("ParentID")]
public int MyParentId { get; set; }
[ForeignKey("MyParentId")]
public Parent MyParent { get; set; }
}
提前致谢
I use EF CTP 5 Code First. If you ask EF to generate database for the model like this it will create appropriate foreign key relationship for you:
public class Parent
{
public ICollection<Child> MyChildren { get; set; }
}
public class Child
{
public Parent MyParent { get; set; }
}
Child table gonna have something like MyParent_Id field as a result of such generation. Now I'm having reverse problem - I have a Db schema which I have to build similar simple model for. By similar simple I mean without any explicit foreign key properties. Is any way to do it?
The only way to do the mapping I found looks like this, but it implies having public property MyParentId in the model which I'm trying to avoid. So how to avoid it?
public class Child
{
[Column("ParentID")]
public int MyParentId { get; set; }
[ForeignKey("MyParentId")]
public Parent MyParent { get; set; }
}
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一种方法是在代码中定义映射而不是使用属性。在“context”类(从
DbContext
派生的类)中:在本例中,“MyParent_Id”是子表中的列名称,而不是
上的任何属性的名称>子
类。One way is to define your mapping in code rather than using attributes. In your "context" class (the one that derives from
DbContext
):In this case, "MyParent_Id" is the name of the column in the child table rather than the name of any property on the
Child
class.