如何摆脱 EF 中的外键属性?

发布于 2024-11-27 22:30:02 字数 635 浏览 8 评论 0原文

我使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

素罗衫 2024-12-04 22:30:02

一种方法是在代码中定义映射而不是使用属性。在“context”类(从 DbContext 派生的类)中:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Child>()
        .HasRequired(c => c.MyParent)
        .WithMany()
        .Map(c => c.MapKey("MyParent_Id"));
}

在本例中,“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):

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Child>()
        .HasRequired(c => c.MyParent)
        .WithMany()
        .Map(c => c.MapKey("MyParent_Id"));
}

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文