我想在ASP.NET MVC4中建立多对多的关系。 目标是使用属于该用户的一列Timeline
对象扩展默认的UserProfile
类。 A Timeline
可以由多个用户共享,所以Timeline
类也应该有一个UserProfile
对象的列表。多对多关系,结表不被识别
Timeline类:
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");
});
}
}
}
用户配置类(与添加的属性默认类):
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: 双上下文也导致问题,两个数据库创建为两个上下文和纯连接表是其中一个是空的。
谢谢。双上下文也造成了问题,两个上下文创建了两个数据库,其中一个上的纯连接表为空。纠正这些后,它工作正常。 –