问题描述
我有一个ASP.NET MVC3应用程序,其中我使用实体框架4.3 code-第一和迁移。
I have an ASP.NET MVC3 application, where I use Entity Framework 4.3 Code-First and Migrations.
我一直在试图创建同一类型的实体之间的许多一对多的关系,但是当我用脚手架迁移的迁移,它会产生一个一对一的关系。
I've been trying to create a many-to-many relationship between entities of the same type, but when I scaffold the migration with Migrations, it generates a one-to-one relationship.
的想法是,一个用户应能跟随多个其他用户(认为微)
The idea is that one user should be able to follow multiple other users (think Twitter).
我的用户
模型是这个样子:
public class User
{
public int UserId { get; set; }
public string Name { get; set; }
public DateTime Registered { get; set; }
...
public virtual ICollection<User> Follows { get; set; }
}
在我的脚手架增加跟随属性,我得到这样一个迁移:
When I scaffold the the added Follows-property, I get a migration like this:
public partial class FollowUser : DbMigration
{
public override void Up()
{
AddColumn("User", "User_UserId", c => c.Int());
AddForeignKey("User", "User_UserId", "User", "UserId");
CreateIndex("User", "User_UserId");
}
...
}
所以,实体框架间$ P $其中pts我的模型,两个用户之间的一对一的关系。
So Entity Framework interprets my model as a one-to-one relationship between two users.
如何创建一个多到许多相同类型的实体之间的关系?
推荐答案
由于它是一个多对多的自我加盟关系,用户实体应该有一个关注
和继类型
属性。因此,让我们改变你的类包括那些用户
两个
Since It is a Many to Many Self Joined relationship, User entity should have a Followers
and Following
properties both of Type User
. So Let us alter your class to include those
public class User
{
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<User> Followers { get; set; }
public virtual ICollection<User> Following { get; set; }
}
现在更新的DbContext类有它返回一个用户属性
Now update the DbContext class to have a Property which returns the Users
public DbSet<User> Users { set; get; }
我们需要告诉的EntityFramework,我们需要有一个许多人在这两者之间的关系很多船。因此,让我们做,与流利的API通过覆盖 OnModelCreating
法
We need to tell EntityFramework that we need to have a many to many relations ship between these two. So Let us do that with Fluent API by overriding OnModelCreating
method
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().HasMany(m => m.Followers).WithMany(p => p.Following).Map(w => w.ToTable("User_Follow").MapLeftKey("UserId").MapRightKey("FollowerID"));
base.OnModelCreating(modelBuilder);
}
现在实体框架将创建表是这样的。
Now Entity Framework will create the tables like this.
请注意,我们明确告诉实体框架使用用户ID 和 FollowerId 作为Forign键列名。如果我们还没有提到的是,EF将使用 USER_ID
和 User_ID1
作为列名。
Note that we explicitly told Entity Framework to use UserId and FollowerId as the Forign Key column name. If we havent mentioned that, EF will use User_ID
and User_ID1
as the column names.
这篇关于在MVC3相同类型的实体之间的许多一对多的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!