c# - 如何使用 Entity Framework 将外键设置为主键?

标签 c# entity-framework ef-fluent-api

我正在尝试使用 Entity Framework 和 Fluent API 将外键设置为主键。

modelBuilder.Entity<Z>()
            .HasRequired(m => m.X)
            .WithRequireDependent(m => m.Y)
            .WillCascadeOnDelete();

我的类(class):

public class Z
{
        [Key,ForeignKey("X")]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public RentCar X { get; set; }
        public DateTime AIA_KM { get; set; }
        public DateTime AIA_FEC { get; set; }
}

我检查了这个 StackoverFlow 问题 Entity Framework Foreign Key as Primary Key Code First以前但对我不起作用。

谢谢。

最佳答案

在您的 Z 实体中添加 RentCar 的 PK 并添加以下配置:

public class Z
{
        public int RentCarId { get; set; }//Add this

        public RentCar X { get; set; }
        public DateTime AIA_KM { get; set; }
        public DateTime AIA_FEC { get; set; }
}

并添加此配置:

modelBuilder.Entity<Z>().HasKey(t => t.RentCarId );// Add this
modelBuilder.Entity<Z>()
            .HasRequired(m => m.X)
            .WithRequireDependent(m => m.Y)
            .WillCascadeOnDelete();

从此link :

Selecting WithRequiredPrincipal will make the entity that you are configuring the principal, meaning it contains the primary key of the relationship. Selecting WithRequiredDependent will make the entity that you are configuring the dependent, meaning it will have the foreign key of the relationship.

因此按照惯例,您的依赖实体 (Z) 的 PK 将是一对一关系的 FK

关于c# - 如何使用 Entity Framework 将外键设置为主键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43258930/

相关文章:

c# - 如何在数据集上运行查询?

c# - C#中如何读取SQL Server发送的Json数据?

entity-framework - 如何在 Entity Framework 中获得行排名

c# - ASP.Net Core 2.0 Web 应用程序中的本地化

c# - 这两个语句有什么区别( Entity Framework )

c# - 在 EF 6 中找不到 HasOne

c# - EF Core Fluent API - 未检测到/未包含在迁移中的唯一约束

entity-framework - 如何在View中获取IdentityUser角色的名称?

c# - tinyMCE 下拉菜单与 'add hyperlink' 模态断开连接

c# - 如何在 EF Code First 中创建/更新 LastModified 字段