2017-03-07 27 views
-1

一個新的DbContext獲取數據我添加了一個新的DbContext到我的項目是這樣的:從使用LINQ

[DbConfigurationType(typeof(MySqlEFConfiguration))] 
public class ApplicationDbContext : IdentityDbContext<ApplicationUser> 
{ 
    public ApplicationDbContext() 
     : base("DefaultConnection") 
    { 
    } 
    public static ApplicationDbContext Create() 
    { 
     return new ApplicationDbContext(); 
    } 

    protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder) 
    { 
     base.OnModelCreating(modelBuilder); 
     modelBuilder.Entity<ApplicationUser>().ToTable("myapp_users"); 
     modelBuilder.Entity<IdentityRole>().ToTable("myapp_roles"); 
     modelBuilder.Entity<IdentityUserRole>().ToTable("myapp_userroles"); 
     modelBuilder.Entity<IdentityUserClaim>().ToTable("myapp_userclaims"); 
     modelBuilder.Entity<IdentityUserLogin>().ToTable("myapp_userlogins"); 
    } 
} 

[DbConfigurationType(typeof(MySqlEFConfiguration))] 
public class MyDbContext : DbContext 
{ 
    public MyDbContext() 
     : base("TestConnection") 
    { 
    } 
    public static MyDbContext Create() 
    { 
     return new MyDbContext(); 
    } 
} 

但是當我嘗試用這個命令得到一些數據:

MyDbContext myContext = new MyDbContext(); 

var products = (from p in myContext.Products 
       select p).ToList(); 

我有此錯誤:

'MyDbContext' does not contain a definition for 'Products' and no extension method 'Products' accepting a first argument of type 'MyDbContext' could be found (are you missing a using directive or an assembly reference?) 

對此有何幫助?如何從新的上下文的數據庫中的表中獲取數據?

+1

'IDbSet Products'在哪裏? –

+0

@HristoYankov我沒有它。我應該爲我在數據庫中的每個表創建新模型嗎? –

+0

我假設你要'代碼優先',對嗎?然後是的,你需要一個'Product'類,你必須添加'public IDbSet Products {get;組; }'在你的db上下文類中。 –

回答

1

如果你先去代碼,那麼你需要一個每個實體的模型,它將映射(生成)到數據庫表中。這通常意味着數據庫將根據您的代碼生成,但是您有現有數據庫的情況下,您仍然使用代碼優先。

即你將需要:

​​

如果你確實有一個現有的數據庫,它可能是你更容易add an EDMX to your project並且從它的上下文。簡單地說,您將與現有數據庫「集成」,而不是生成一個。

+0

然後我將使用EDMX。這次真是萬分感謝! –