简体   繁体   English

如何为 ASP.Net 身份用户 model 创建关系(一对一、多对多)

[英]How to create relationships (one-to-one, many-to-many) for ASP.Net Identity Users model

I need create 2 relationships for Identity.User我需要为 Identity.User 创建 2 个关系

  1. One-to-One (i know, that is so bad, but i need this)一对一(我知道,这很糟糕,但我需要这个)

For example, to set additional user characteristics.例如,设置其他用户特征。

  1. Many-to-Many多对多

For example, for model of Books.例如,对于书籍的 model。 User can have many books and a book can be with many users.用户可以有很多书,而一本书可以有很多用户。 Like in the library.就像在图书馆一样。

How I can do this.我怎么能做到这一点。 Thanks.谢谢。

First of all.首先。 Many to Many Foreign Keys are not supported in SQL Server. SQL 服务器不支持多对多外键。 The only way to achieve this (at least the only way I know) is to create a "mapping" table.实现这一点的唯一方法(至少我知道的唯一方法)是创建一个“映射”表。

So you need three tables User, Books and UserBooks.所以你需要三个表 User、Books 和 UserBooks。

I will not dive into the details on how to do it but I will point you in the right direction.我不会深入探讨如何做的细节,但我会为你指明正确的方向。

Here is a Many To Many Tutorial on how to do this.这是有关如何执行此操作的多对多教程

Here is Another Tutorial这是另一个教程

The second one shows the table schema.第二个显示表模式。 This is pretty common.这很常见。

I hope this helps you achieve your goal.我希望这可以帮助您实现目标。

You can inherit from IdentityUser and pass your custom object that inherits from it in IdentityDbContext<> .您可以从IdentityUser继承并在IdentityDbContext<>中传递从它继承的自定义 object 。 Then your custom object can have additional members that you need including collection of books or singular properties.然后,您的自定义 object 可以具有您需要的其他成员,包括书籍集合或单一属性。

Then you define the relationship when overriding OnModelCreating as specified here然后,您在按照此处指定的覆盖OnModelCreating时定义关系

As a rough example:作为一个粗略的例子:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<CustomUser>()
        .HasOne(p => p.Name)
        .WithMany(b => b.Books);
}

Hope this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM