![](/img/trans.png)
[英]Relationship between Identity tables and Other tables in ASP.NET MVC 5
[英]How to make relationship between tables in asp.net mvc?
我在项目中使用“ AspIdentity”。 在项目中,所有“ AspIdentity”标准模型和一个“ Post”模型。 我希望每个帖子都有其ApplicationUser,每个ApplicationUser都有自己的帖子集合。 并且已经有一个数据库,其中有一个表来存储有关用户的信息。
我尝试独立创建表,数据上下文和数据库,但没有找到任何信息,但没有找到与我的案件有关的信息。
帖子模型:
public class Post
{
public int Id { get; set; }
public string Body { get; set; }
public string ApplicationUserId { get; set; }
public ApplicationUser ApplicationUser { get; set; }
}
ApplicationUser模型:
public class ApplicationUser : IdentityUser
{
public int Year { get; set; }
public virtual ICollection<Post> Posts { get; set; }
public ApplicationUser()
{
Posts = new List<Post>();
}
}
我希望在响应中看到一个数据上下文,并在查询中创建一个帖子表。
您需要在DbContext类(可能是ApplicationDbContext)中重写OnModelCreating方法。 在重写方法中,建立类之间的关系。 以下是应解决您的问题的示例代码:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ApplicationUser>()
.HasMany(e => e.Posts)
.WithRequired(e => e.ApplicationUser)
.HasForeignKey(e => e.ApplicationUserId)
.WillCascadeOnDelete(false);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.