【问题标题】:Entity framework creating separate database corresponding to each class in model实体框架创建对应于模型中每个类的单独数据库
【发布时间】:2013-04-25 13:25:38
【问题描述】:

我已经开始在 ASP.NET MVC4 中使用实体框架了。

我在Model 文件夹中创建了 3 个类,并为每个模型创建了控制器。

现在,当我运行应用程序时,它已经创建了与每个​​模型类对应的单独数据库。

有什么方法可以让我们只使用一个数据库?

【问题讨论】:

  • 你的上下文是如何定义的?
  • 请发布您的上下文类。
  • 我的上下文类就像-'public class EmployeeDbContext : DbContext { public DbSet Employees { get;放; } }'
  • 我的上下文类是这样的- 1. 这是我的模型类public class Employee { [Key] public int EmpId { get; set; } [Required] public string FullName { get; set; } [Required] public string DateOfBirth { get; set; } [Required] public string Designation { get; set; } [Required] public string Email { get; set; } [Required] public string Gender { get; set; } [Required] public string ContactNo { get; set; } [Required] public string Role { get; set; } }
  • 这是我的上下文类

标签: c# asp.net sql-server asp.net-mvc-4 entity-framework-5


【解决方案1】:

您是否为每个类创建单独的上下文?

public class Employee 
{
    [Key] public int EmpId { get; set; } // < Can I make a suggestion here
                                         // and suggest you use Id rather than
                                         // EmpId?  It looks better referring to 
                                         // employee.Id rather than employee.EmpId
    [Required] public string Fullname { get; set; }
    ...
}

public class AnotherClass
{
    ...
}

然后在上下文中列出所有模型:

public MyDbContext : DbContext
{
    public DbSet<Employee> Employees { get; set; }
    public DbSet<AnotherClass> AnotherClasses { get; set; }
}

您可能还想通过在上下文中使用构造函数来指定连接字符串名称:

public MyDbContext() : base("ConnectionString") {  }

重要的是所有模型都在同一个上下文中。

使用上下文

var context = new MyDbContext();
var employees = context.employees.ToList(); // I prefer storing the data as an IList

这告诉 EF 查询数据库并将数据存储在 employees 变量中。

【讨论】:

  • 感谢您的回复。您是说我应该在一个类中创建所有 DbSet。但我认为,如果我创建“MyDbContext”类的对象,它将为该类中的所有 DbSet 分配内存。让我知道,如果我错了或者我的想法是对的,我们该如何避免这种情况。
  • 我认为您误解了 ef 的工作原理。当您使用 context.employees.ToList() 时,它此时会查询数据库并使用内存。将它列在一个类中不会。
  • 感谢您的回复。现在我明白了。
猜你喜欢
  • 1970-01-01
  • 2013-03-29
  • 2017-07-11
  • 2023-03-29
  • 2017-08-10
  • 2017-10-04
  • 2017-07-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多