gpt4 book ai didi

c# - Entity Framework 创建与模型中每个类对应的单独数据库

转载 作者:行者123 更新时间:2023-11-30 12:47:41 25 4
gpt4 key购买 nike

我已经开始在 ASP.NET MVC4 中使用 Entity Framework 。

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

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

有什么办法可以只使用一个数据库吗?

最佳答案

您要为每个类创建单独的上下文吗?

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 变量中。

关于c# - Entity Framework 创建与模型中每个类对应的单独数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16216014/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com