c# - EF 7(Beta 7)一对一关系

标签 c# entity-framework entity-framework-core

我注意到一些问题已经在 EF 7 的早期测试版中解决了这个问题(例如 here ),但我还没有看到它在 Beta 7 中得到解决,所以这里是:

我有 2 个实体,简化如下:

public class FirstEntity
{
    public int FirstEntityID { get; set; }
    /*
        Other fields here
    */
    public int? SecondEntityID { get; set; }
    public SecondEntity SecondEntityProperty { get; set; }
}

public class SecondEntity
{
    public int FirstEntityID { get; set; } 
    /*
        Other fields here
    */
    public FirstEntity FirstEntityProperty { get; set; }
}

与早期版本相比,映射所有内容的方式发生了很大变化。如何将这两个实体映射为一对一关系?

最佳答案

EF7 rc1-final 已更改。

modelBuilder.Entity<FirstEntity>()
            .HasOne(q => q.SecondEntity)
            .WithMany()
            .HasForeignKey(q => q.SecondEntityID);

更新:

modelBuilder.Entity<FirstEntity>()
            .HasOne(q => q.SecondEntity)
            .WithOne(v => v.FirstEntity)
            .HasForeignKey<FirstEntity>(q => q.SecondEntityID);

关于c# - EF 7(Beta 7)一对一关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32530795/

相关文章:

c# - 无法在 ASP.Net MVC 3 项目中使用 Entity Framework 保存更改

c# - EF Core 是否可以将 OnModelCreating/ConfigureConventions 中的代码作为迁移代码生成的一部分?

c# - 公共(public) API 如何管理负载?

c# - DidReceiveRemoteNotification 未在后台调用 - Xamarin iOS - 推送通知

asp.net-mvc - 数据模型需要两个属性之一

asp.net-core - 使用 EFcore/ASP.net core 更新查找表中的数据的正确方法?我是用种子方法还是其他方法来做到这一点?

c# - 我可以在向服务添加 DbContext 之前从容器获取服务吗?

c# - 绑定(bind)到属性的 WPF Datagrid RowDetailsTemplate 可见性

c# - P/Invoke 为目标 DLL 提供的内存是否较少?

entity-framework - 任何指向 DbSet 属性名称的信息吗?