我想在 ASP.NET MVC4 中建立多对多关系。目标是使用属于用户的对象列表扩展默认UserProfile
类。Timeline
ATimeline
可以由多个用户共享,因此Timeline
该类也应该有一个UserProfile
对象列表。
时间线类:
namespace MvcApplication1.Models
{
public class Timeline
{
public int Id { get; set; }
public string Name { get; set; }
public string Color { get; set; }
public List<UserProfile> Users { get; set; }
}
public class TimelineContext : DbContext
{
public DbSet<Timeline> Timelines { get; set; }
public DbSet<UserProfile> UserProfiles { get; set; }
// Added the following because I saw it on:
// http://www.codeproject.com/Tips/548945/Generating-Many-to-Many-Relation-in-MVC4-using-Ent
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Timeline>()
.HasMany(c => c.Users)
.WithMany(s => s.Timelines)
.Map(mc =>
{
mc.ToTable("TimelineOwners");
mc.MapLeftKey("TimelineId");
mc.MapRightKey("UserId");
});
}
}
}
UserProfile 类(具有附加属性的默认类):
public class UsersContext : DbContext
{
public UsersContext()
: base("DefaultConnection")
{
}
public DbSet<UserProfile> UserProfiles { get; set; }
public DbSet<Timeline> Timelines { get; set; }
// Added the following because I saw it on:
// http://www.codeproject.com/Tips/548945/Generating-Many-to-Many-Relation-in-MVC4-using-Ent
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<UserProfile>()
.HasMany(c => c.Timelines)
.WithMany(s => s.Users)
.Map (mc =>
{
mc.ToTable("TimelineOwners");
mc.MapLeftKey("UserId");
mc.MapRightKey("TimelineId");
});
}
}
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public List<Timeline> Timelines { get; set; }
}
我有一个带有外键的连接表:
创建 的实例时Timeline
,Users
列表为null
:
Timeline timeline = db.Timelines.Find(id); // timeline.Users = null
有人可以启发我,我应该如何设置它?
我对 ASP.NET MVC4 完全陌生。
编辑 1:我知道我不应该扩展 UserProfile 而是创建另一个类来存储用户。一旦多对多关系起作用,我将重构并朝那个方向发展。但首先我想知道为什么它不起作用。
编辑2: 双重上下文也引起了问题,为这两个上下文创建了两个数据库,其中一个纯连接表为空。