2017-03-07 59 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。这次真是万分感谢! –