我正在尝试使用 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. SelectingWithRequiredDependent
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/