【发布时间】:2013-07-01 06:26:57
【问题描述】:
我想在 ASP.NET MVC4 中建立多对多关系。
目标是使用属于用户的Timeline 对象列表扩展默认的UserProfile 类。
一个Timeline 可以被多个用户共享,所以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: 双重上下文也引起了问题,为这两个上下文创建了两个数据库,其中一个纯连接表为空。
【问题讨论】:
标签: asp.net asp.net-mvc entity-framework asp.net-mvc-4