因此,我目前正在尝试使用实体框架核心为表格显示应用程序用户已完成哪些演讲,并首次创建代码。我的模型是这样的:实体框架核心“实体类型'XXX'需要定义主键。”
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
作为独特的复合键。但我得到这个错误:
The entity type 'LectureCompletion' requires a primary key to be defined.
我不明白为什么会发生这种情况,因为我清楚地有我的关键属性在正确的位置?我能否使用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);
}
}
真棒!谢谢!这工作和学习了一些事情阅读您提供的链接。只是想补充说外键UserId需要是一个字符串而不是int。 –