gpt4 book ai didi

c# - AspNetUsers (Identity) 和自定义表之间的一对多关系

转载 作者:可可西里 更新时间:2023-11-01 06:32:35 24 4
gpt4 key购买 nike

我非常想在 Identity 2.0 的 AspNetUsers 表和一个名为 Map 的自定义表之间创建一对多关系(一个用户可以有很多 map ,但一个 map 只能有一个用户)我已经尝试了大部分本网站提供的解决方案也浪费了很多天尝试在网络上找到的其他解决方案。我卡住了。似乎没有什么适合我。我是 MVC 和 EF 的新手,所以基本上我认为我需要某种分步指南。任何人都可以非常友好地为我提供一个新手指南,以从一个新制作的 MVC5 项目中实现这一目标。感谢和抱歉我提出的冗余问题。

附言。我可以而且我成功地在两个自定义表之间创建了各种关系,但不是在 AspNetUsers 和我的 map 表之间。非常非常感谢。

最佳答案

我已经在很多项目中做到了这一点

例如,我有一个从 ASPNetUsers 到通知的一对多关系。所以在 IdentityModels.cs 的 ApplicationUser 类中我有

public virtual ICollection<Notification> Notifications { get; set; }

我的通知类有相反的

public virtual ApplicationUser ApplicationUser { get; set; }

默认情况下,EF 会创建一个从 Notification 到 AspNetUsers 的级联删除,这是我不想要的 - 所以我的 Context 类中也有这个

modelBuilder.Entity<Notification>()
.HasRequired(n => n.ApplicationUser)
.WithMany(a => a.Notifications)
.HasForeignKey(n => n.ApplicationUserId)
.WillCascadeOnDelete(false);

请记住,AspNetUSers 的定义是在 IdentityModels.cs 中的 ApplicationUser 类中扩展的,它由 visual studios 脚手架为您生成。然后将其视为您应用中的任何其他类/表

更新 - 这里是完整模型的例子

public class ApplicationUser : IdentityUser
{

[StringLength(250, ErrorMessage = "About is limited to 250 characters in length.")]
public string About { get; set; }

[StringLength(250, ErrorMessage = "Name is limited to 250 characters in length.", MinimumLength=3)]
public string Name { get; set; }

public DateTime DateRegistered { get; set; }
public string ImageUrl { get; set; }

public virtual ICollection<Notification> Notifications { get; set; }

public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}


public class Notification
{
public int ID { get; set; }

public int? CommentId { get; set; }

public string ApplicationUserId { get; set; }

public DateTime DateTime { get; set; }

public bool Viewed { get; set; }

public virtual ApplicationUser ApplicationUser { get; set; }

public virtual Comment Comment { get; set; }

}

关于c# - AspNetUsers (Identity) 和自定义表之间的一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29793926/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com