如何使用 Entity Framework 将外键设置为主键?
How can I set a foreign key as primary key with Entity Framework?
我正在尝试使用 Entity Framework 和流畅的 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; }
}
我之前检查过这个 Whosebug 问题 Entity Framework Foreign Key as Primary Key Code First,但对我不起作用。
谢谢。
在你的 Z
实体中添加 RentCar
的主键并添加以下配置:
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
我正在尝试使用 Entity Framework 和流畅的 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; }
}
我之前检查过这个 Whosebug 问题 Entity Framework Foreign Key as Primary Key Code First,但对我不起作用。
谢谢。
在你的 Z
实体中添加 RentCar
的主键并添加以下配置:
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