所以我目前正在尝试使用实体框架核心为一个表创建代码优先迁移,该表显示应用程序用户已完成的讲座。我的模型如下所示:
public class LectureCompletion
{
[Key, Column(Order = 0)]
[ForeignKey("Lecture")]
public Lecture LectureId { get; set; }
[Key, Column(Order = 1)]
[ForeignKey("User")]
public ApplicationUser UserId{ get; set; }
public bool Completed { get; set; }
}
我想使用UserId
和LectureId
作为唯一的组合键。但是我收到此错误:
实体类型"讲座完成"需要定义主键。
我不明白为什么会发生这种情况,因为我显然在正确的位置上拥有我的关键属性?是否可以将ApplicationUser
用作外键/主键?
这是我Lecture
模型:
public class Lecture
{
[Key]
public int LectureId { get; set; }
public string ModuleName { get; set; }
public string LectureName { get; set; }
}
而我的ApplicationDBContext.cs
:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public DbSet<Lecture> Lectures { get; set; }
public DbSet<LectureCompletion> LectureCompletion { get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
}
}
不能仅使用数据注释来定义组合键。您需要改用 Fluent API。
public class LectureCompletion
{
// which is your case.
[ForeignKey(nameof(Lecture))]
public int LectureId { get;set; }
public Lecture Lecture { get; set; }
[ForeignKey(nameof(ApplicationUser))]
public int UserId {get;set;}
public ApplicationUser ApplicationUser { get; set; }
public bool Completed { get; set; }
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Define composite key.
builder.Entity<LectureCompletion>()
.HasKey(lc => new { lc.LectureId, lc.UserId });
}
https://learn.microsoft.com/en-us/ef/core/modeling/keys
您的LectureCompletion
类需要正确定义主键。[Key]
是主键注释,用于显式告诉 EntityFramework 将其设置为主键,否则约定将接管。
也就是说,以 ID
命名或后缀为 ID
的属性,例如 PokemonID
Pokemon
表。 在这种情况下,ID
或Id
不区分大小写。
名称与引用的类命名不同时LectureCompletion
才使用外键属性。例如,如果ApplicationUser
类的主键是 ApplicationUserId
,但在LectureCompletion
类中您希望它UserId
则可以添加该属性。
像这样做
public class LectureCompletion
{
[Key] // Defined only once
public LectureCompletionId { get;set; }
// Not needed if Lecture class has the primary key property of LectureId,
// which is your case.
[ForeignKey("Lecture")] // Name of your navigation property below.
public int LectureId { get;set; }
public Lecture Lecture { get; set; }
[ForeignKey("ApplicationUser")]
public int UserId {get;set;}
public ApplicationUser ApplicationUser { get; set; }
public bool Completed { get; set; }
}
至于EntityFramework Core,ColumnOrder目前似乎没有任何影响。