实体框架与现有数据库

B V*_*hya 7 entity-framework

我想在我现有的项目中实现实体框架版本4.3.1,它不遵循这个EF.数据库已经开发并且目前用于应用ado.net.在这种情况下我该如何开始使用EF ,是数据库优先,代码优先.

And*_*eza 14

即使数据库已经存在,我仍然使用Code First方法,使用注释映射表,因为域的组织方式比EDMX文件更有条理.如果有很多表格,那么视觉EDMX可能变得毫无用处,因为设计将遍布整个地方的数据和连接过度拥挤.

您可以从两个步骤开始:

1)Customer例如,创建一个域模型类,并使用数据注释将其映射到您的表:

[Table("tbl_cust")]
public class Customer
{
    [Key]
    [Column("cust_id")]
    public int CustomerId { get; set; }
    [Column("cust_name")]
    public string Name { get; set; }
    // Add other properties below
 }
Run Code Online (Sandbox Code Playgroud)

2)创建一个从每个模型派生DbContext并设置DbSet<T>属性的上下文类,在我们的例子中只有一个:

public class MyApplicationContext: DbContext
{
    public MyApplicationContext() : base("name=ConnectionStringName") { }

    public DbSet<Customer> Customers { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

现在,您的代码中的任何位置都可以实例化派生DbContext类并使用Linq进行查询:

var _db = new MyApplicationContext();
var customer = _db.Customers.Where(c => c.CustomerId == 37).FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

不要忘记使用NuGet添加对EntityFramework程序集的引用.

祝好运.