public class Department { [Key] public int ID { get; set; } = 0; [Required] public string Name { get; set; } = ""; public virtual ICollection<User> Users { get; set; } }
public class User { [Key] public int ID { get; set; } = 0; public int DepartID { get; set; } = 0; [StringLength(30)] public string Username { get; set; } = ""; [ForeignKey("DepartID")] public virtual Department Department { get; set; } }
protected override void Seed(GCSecurity.MVC.DAL.GCDbContext context) { var departs = new List<Department> { new Department{ ID = 1, Name = "办公室" } }; articles.ForEach(s => context.Articles.Add(s)); context.SaveChanges(); context.Users.Add(new User { ID = 1, Username = "admin", DepartID = 1 }); context.SaveChanges(); }
执行update-database 时,System.Data.SqlClient.SqlException: INSERT 语句与 FOREIGN KEY 约束"FK_dbo.User_dbo.Department_DepartID"冲突。该冲突发生于数据库"GCSecurity",表"dbo.Department", column 'ID'。
正常的,谁让你用INT自增做主键呢。只能自己想想咋办咯。
应该使用什么类型做主键
@老S: 哦,你 new department 的时候别加 id就行了。
至于下面 users 怎么关联,你自己想一想。
建议将User模型中的DepartID更新为
public int? DepartID { get; set; } = 0;