2016-05-28 140 views
0

我想寫自定義DBInitializer一個ASP MVC應用程序,但我發現了錯誤:實體框架6:指用戶配置

Additional information: The member with identity 'MailMail.Models.MailDbContext.Video_UserProfile' does not exist in the metadata collection.

我有視頻類:

public class Video : Entity 
{ 
    public string Name { get; set; } 
    public string Path { get; set; } 
    public virtual UserProfile UserProfile { get; set; } 
} 

而且我的DBInitializer:

public class MailDbInitializer : DropCreateDatabaseAlways<MailDbContext> 
    { 
     protected override void Seed(MailDbContext context) 
     { 
      UsersContext userContext = new UsersContext(); 

      if (!WebMatrix.WebData.WebSecurity.Initialized) 
      { 
       WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true); 
      } 


      var mongol1 = new { Email="[email protected]", UserName="Tom"}; 
      var mongol2 = new { Email = "[email protected]", UserName = "Karola" }; 
      WebSecurity.CreateUserAndAccount(mongol1.UserName, "secret", mongol1); 

      Task<UserProfile> user1Task = userContext.UserProfiles.SingleOrDefaultAsync(o => o.UserName == mongol1.UserName); 
      user1Task.Wait(); 
      UserProfile user1 = user1Task.Result; 

      WebSecurity.CreateUserAndAccount(mongol2.UserName, "123456", mongol2); 
      Task<UserProfile> user2Task = userContext.UserProfiles.SingleOrDefaultAsync(o => o.UserName == mongol2.UserName); 
      user2Task.Wait(); 
      UserProfile user2 = user1Task.Result; 



      Video video1 = new Video() {Name="Moje wideo", UserProfile=user1, Path = "~/App_Data/"+user1.UserId+"/Video1"}; 
      Video video2 = new Video() { Name = "Moje wideo", UserProfile = user1, Path = "~/App_Data/" + user1.UserId + "/Video2" }; 
      Video video3 = new Video() { Name = "Moje wideo", UserProfile = user2, Path = "~/App_Data/" + user2.UserId + "/Video3" }; 
      Video video4 = new Video() { Name = "Moje wideo", UserProfile = user2, Path = "~/App_Data/" + user2.UserId + "/Video4" }; 

      context.Videos.Add(video1); //HERE ocures the error! 
      context.Videos.Add(video2); 

我認爲這可能與不同的上下文有關。我對嗎?

回答

0

問題是我有2個不同的上下文,他們都指向相同的數據庫。 我的解決辦法是:我只是複製

public DbSet<UserProfile> UserProfiles { get; set; } 

我的主要的DbContext類。 解決了這個問題:-)