2015-04-23 45 views
1

我發現問題,解決方法是在評論。不能用EF代碼優先種子數據

我可以創建表格和圖表,但我不能將數據種子到表格。

1.我通過Nuget安裝了EF。

2.從PM控制檯我寫了Enable-Migrations -EnableAutomaticMigrations。

模型是All.Model類庫和和上下文是All.Dal類庫我不明白我做錯了,你能幫我嗎?

這是我的上下文代碼:

using All.Model; 

namespace All.Dal 
{ 
    public class AllDb : DbContext 
    { 
    public AllDb() 
    { 
     Database.Connection.ConnectionString = "Server=SEUPHORIA;Database=AllDb;UID=sa;PWD=123;"; 
    } 

    public DbSet<Category> Categories { get; set; } 
    public DbSet<Comment> Comments { get; set; } 
    public DbSet<Line> Lines { get; set; } 
    public DbSet<User> Users { get; set; } 

    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     Database.SetInitializer<AllDb>(new DbStrategy()); 
     modelBuilder.Entity<Category>().Property(c => c.Name).IsRequired(); 
     modelBuilder.Entity<Comment>().Property(c => c.Letter).IsRequired(); 
    } 
} 

}

這是我的策略代碼:

using All.Model; 

namespace All.Dal 
{ 
    public class DbStrategy : DropCreateDatabaseIfModelChanges<AllDb> 
    { 
     protected override void Seed(AllDb context) 
    { 
     List<Category> CategoryDefault = new List<Category> 
     { 
      new Category { Name="Organic", UpID = 0 }, 
      new Category { Name="Object", UpID=0}, 
      new Category { Name="Time",UpID=0}, 
     }; 

     foreach (Category item in CategoryDefault) 
     { 
      context.Categories.Add(item); 
     } context.Users.Add(new User { Name = "sss" }); 

    } 
} 

}

這是我的類別類:

public class Category : Standart 
    { 
    public int UpID { get; set; } 
    public string Name { get; set; } 
    public int LineID { get; set; } 
    public virtual List<Line> Lines { get; set; } 
} 
+0

你能共享分類表模式嗎? – prashant

+0

我已經添加了類 – Seuphoria

+1

請檢查了這一點http://stackoverflow.com/questions/17044162/cannot-insert-by-using-entity-framework – prashant

回答

1

您正在將項目添加到數據庫上下文中,但未通過調用SaveChanges()對它們進行提交。只需添加這一行:

protected override void Seed(AllDb context) 
{ 
    List<Category> CategoryDefault = new List<Category> 
    { 
     new Category { Name="Organic", UpID = 0 }, 
     new Category { Name="Object", UpID=0}, 
     new Category { Name="Time",UpID=0}, 
    }; 

    foreach (Category item in CategoryDefault) 
    { 
     context.Categories.Add(item); 
    } 
    context.Users.Add(new User { Name = "sss" }); 
    context.SaveChanges(); // make sure you save! 
} 
+0

它是上下文而不是數據庫,你不能使savechanges.Btw我試過,但沒有奏效。 – Seuphoria

+0

爲什麼你不能使用[DbContext.SaveChanges()](https://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext.savechanges%28v=vs.113%29.aspx) ?當你嘗試時它會做什麼? – br4d

+0

我發現問題,因爲prashanth說我發送空數據到不可空列.AndChangeChanges保存數據第一上下文後數據庫不僅上下文感謝您的幫助。 – Seuphoria