c# – AspNetUsers’ID作为外键分离表,一对一关系

前端之家收集整理的这篇文章主要介绍了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")
    {
    }

}

我得到这个错误,引用

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.

我也尝试过这个人的方法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; }
}
原文链接:https://www.f2er.com/csharp/96393.html

猜你在找的C#相关文章