目前这是我所拥有的
楷模
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") { } }
我得到这个错误,引用
Unable to determine the principal end of an association between the types ‘TestApplication.Models.Customer’ and ‘TestApplication.Models.ApplicationUser’. 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状态:
If you add the ForeigKey attribute to a foreign key property,you
should specify the name of the associated navigation property. If you
add the ForeigKey attribute to a navigation property,you should
specify the name of the associated foreign key(s).
我解释这一点,因为应该可以将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; } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。