我有两个表项目和任务.任务是项目的弱实体,因此任务的复合主键是(ProjectId& TaskID).我尝试使用以下代码,但它给出了一个错误
Cannot define PRIMARY KEY constraint on nullable column in table ‘Tasks’.
我正在使用代码优先的方法来创建表,我确保列不是null,但它仍然无法正常工作.请帮忙!
public class Task { [ForeignKey("ProjectId")] public Project Project { get; set; } [required] public int ProjectId { get; set; } //[Key,Column(Order = 1)] [required] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public virtual int TaskID { get; set; } ... } //using FluentAPI protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<Task>().Hasrequired(p => p.Project); modelBuilder.Entity<Task>().HasKey(p => new { p.ProjectId,p.TaskID }); modelBuilder.Entity<Project>() .Hasrequired(e=> e.Employee) .WithMany() .WillCascadeOnDelete(false); }
解决方法
遇到这个寻找别的东西,有点晚了,但这对我来说很好地映射到一个复合键
[Key,Column(Order=1) ] public int KeyId { get; set; } [Key,Column(Order = 2)] public int Key1Id { get; set; } [Key,Column(Order = 3)] public int Key2Id { get; set; } [Key,Column(Order = 4)] public int Key3Id { get; set; }
希望这有助于某人.