c# – AspNetUsers’ID作为外键分离表,一对一关系
我已经查找起来,尝试所有不同的和各种各样的方式可以将AspNetUser表的外键存储在单独的Customer表中.我仍然是ASP.NET和实体框架的新功能,但我已经阅读了不少帖子和文档.
目前这是我所拥有的 楷模 public class Customer { [Display (Name="Customer ID")] public int CustomerID { get; set; } public string UserId { get; set; } [ForeignKey("UserId")] public virtual ApplicationUser ApplicationUser { get; set; } } public class ApplicationUser : IdentityUser { public virtual Customer Customer { get; set; } } public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public DbSet<Customer> Customers { get; set; } public ApplicationDbContext() : base("DefaultConnection") { } } 我得到这个错误,引用
我也尝试过这个人的方法:The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations 所以我评论了ForeignKey注释,并使用了这个人的建议,使用了“modelBuilder”的方法.当我更新了我的数据库时,AspNetUsers表中的“Id”位于Customers表中(这是很好的),但是作为ForeignKey的CustomerID也在AspNetUsers表中,这不是我想要的. 我想要的是,AspNetUsers的“Id”作为ForeignKey在Customers表中. 解决方法
在一对一的关系中,“孩子”表,在您的情况下,客户应该具有与相关表相同的主键,即外键.
您提供的代码示例意味着,在客户端,您将拥有一个不同于UserId的名为CustomerID的PK. 这应该在你的情况下工作(未测试): public class Customer { [Key] public string UserId { get; set; } [ForeignKey("UserId")] public virtual ApplicationUser ApplicationUser { get; set; } } public class ApplicationUser : IdentityUser { public virtual Customer Customer { get; set; } } 编辑: MSDN for ForeignKeyAttribute状态:
我解释这一点,因为应该可以将ForeignKey属性添加到导航属性或外键属性,并且任何一种方式都应该可以工作,但显然不是.按照下方移动它应该做的诀窍. public class Customer { [Key,ForeignKey("ApplicationUser")] public string UserId { get; set; } public virtual ApplicationUser ApplicationUser { get; set; } } public class ApplicationUser : IdentityUser { public virtual Customer Customer { get; set; } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |