简体   繁体   English

将ASP.NET身份用户链接到Books表

[英]Link ASP.NET Identity Users to Books Table

I've used the default WebApi template with Individual Authorization for my project. 我为项目使用了带有“个人授权”的默认WebApi模板。 I've successfully registered accounts, and edited the model and controller so that the UserName is stored in the Username field instead of the email, which is how it is by default. 我已经成功注册了帐户,并编辑了模型和控制器,以便将UserName存储在Username字段中,而不是电子邮件中,默认情况下是这样。

I am trying to create a Book table with the following model : 我正在尝试使用以下模型创建Book表:

public int Id { get; set; }
[Required]
public string Title { get; set; }
public string Description { get; set; }
public int Ratings { get; set; }

// Foreign Key
public string Username { get; set; }
// Navigation property
public Guid Guid { get; set; }

I want to use the UserName as the foreign key since it is unique. 我想使用UserName作为外键,因为它是唯一的。 Can anyone tell me if this is correct. 谁能告诉我这是否正确。 I'm not sure the navigation property. 我不确定导航属性。

For having a Foreign Key, the standard examples say that you should have something like this: 对于具有外键,标准示例说明您应该具有以下内容:

public Guid UserId { get; set; }
[ForeignKey(nameof(UserId))]
public virtual User User { get; set; }

This allows you to use UserId as the Foreign Key , at the same time the entire User object is lazily available to you. 这使您可以将UserId用作Foreign Key ,同时整个User对象对您都是惰性的。 You could use this property to access the Book.User.Username in your code. 您可以使用此属性访问代码中的Book.User.Username

It makes little sense to have a column containing the the actual Username s. 包含实际Username的列几乎没有意义。 Tomorrow, if you wish to have the user's Email , you will have to add another column in your Books table. 明天,如果您希望拥有用户的Email ,则必须在Books表中添加另一列。 But with the above example, you merely need to access Book.User.Email in the code. 但是在上面的示例中,您只需要访问代码中的Book.User.Email

(Tip: Using the Id column is fast is it is the PK in the Foreign table and hence Indexed .) (提示:使用Id列是快速的,因为它是Foreign表中的PK ,因此是Indexed 。)

(Tip2: Avoid Guid as the type for Id column. Personally, I use `long, which is more efficient with respect to indexing and has a reasonable range) (提示2:避免将Guid用作Id列的类型。就我个人而言,我使用`long,这在索引编制方面更有效并且具有合理的范围)

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

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