Ser*_*rca 8 c# mysql entity-framework asp.net-mvc-5 asp.net-identity-2
我迫切希望在Identity 2.0的AspNetUsers表和一个名为Map的自定义表之间创建一对多的关系(一个用户可以有很多地图,但一个地图只能有一个用户)我已经尝试了大多数可用的解决方案这个网站也失去了很多天尝试在网络上找到的其他soulutions.我被卡住了.似乎没有什么对我有用.我是MVC和EF的新手,所以基本上我认为我需要一些循序渐进的指南.任何人都可以非常友好地为我提供一个新手指南,以实现这一点,从一个新的MVC5项目.谢谢,对不起我提出的冗余问题.
PS.我可以成功创建两个自定义表之间的关系,但不能在AspNetUsers和我的Map表之间创建.非常感谢提前.
Sym*_*een 11
我在很多项目中做到了这一点
例如,我有一个从ASPNetUsers到Notifications的一对多关系.所以我在IdentityModels.cs里面的ApplicationUser类中有
public virtual ICollection<Notification> Notifications { get; set; }
Run Code Online (Sandbox Code Playgroud)
我的通知类具有相反的功能
public virtual ApplicationUser ApplicationUser { get; set; }
Run Code Online (Sandbox Code Playgroud)
默认情况下,EF将创建从Notification到AspNetUsers的级联删除,我不想要 - 所以我也在我的Context类中有这个
modelBuilder.Entity<Notification>()
.HasRequired(n => n.ApplicationUser)
.WithMany(a => a.Notifications)
.HasForeignKey(n => n.ApplicationUserId)
.WillCascadeOnDelete(false);
Run Code Online (Sandbox Code Playgroud)
请记住,AspNetUSers的定义是在Visual Studio脚手架为您生成的IdentityModels.cs中的ApplicationUser类中进行了扩展.然后将其视为应用中的任何其他类/表
更新 - 以下是完整模型的示例
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; }
}
Run Code Online (Sandbox Code Playgroud)
}
归档时间: |
|
查看次数: |
9298 次 |
最近记录: |