我想在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: 雙上下文也導致問題,兩個數據庫創建爲兩個上下文和純連接表是其中一個是空的。
謝謝。雙上下文也造成了問題,兩個上下文創建了兩個數據庫,其中一個上的純連接表爲空。糾正這些後,它工作正常。 –