【发布时间】:2012-06-17 15:54:01
【问题描述】:
我一直在尝试将 MVC 4.0 与 EF 4.3 和数据库迁移结合使用,正如 Scott Gu 在 Tech Days 上介绍的那样,并且遇到了在存在多对多关系时创建的数据库的问题。
http://channel9.msdn.com/Events/TechDays/Techdays-2012-the-Netherlands/2364 21:14 开始
包括用于生成数据库的代码的 sn-ps,如下图所示。
public class Trip {
public int ID { get; set; }
public string Name { get; set; }
public DateTime Begin { get; set; }
public DateTime End { get; set; }
public Location HomeCountry { get; set; }
//public IList<Location> Itinerary { get; set; }
public ICollection<Location> Itinerary { get; set; }
public Trip()
{
this.Itinerary = new HashSet<Location>();
}
}
public class Location
{
public int ID { get; set; }
public string Name { get; set; }
public ICollection<Trip> Trips { get; set; }
public Location()
{
this.Trips = new HashSet<Trip>();
}
}
这是生成的数据库。 (我会发一张图片,但我无法发布图片,仍然是新用户)
表 地点 PK ID(整数) 名称(varchar) Trip_ID (int) 旅行 PK ID(整数) 名称(varchar) 开始(日期时间) 结束(日期时间) HomeCountry_ID (int)我想我希望为 Locations 和 Trips 之间的多对多关系创建第三个关系表(许多 Locations 可以应用于许多 Trips),而不是将 Trip_Id 列添加到 Locations 表中。有谁知道我在这里做错了什么?有没有办法让数据库自动化来正确创建这些表?
提前感谢您的所有帮助!
更新: 我找到了以下链接,但我仍然无法使用 EF 4.3 让它工作。我还编辑了我的代码 sn-ps 以反映以下帖子。
http://www.codeproject.com/Articles/234606/Creating-a-Many-To-Many-Mapping-Using-Code-First
【问题讨论】:
-
你是用fluent api还是什么来建立关系的?我需要看看。
-
@John 目前我正在研究这个只是为了掌握我观看的演示文稿并了解这对于简单项目有多么有用。我使用 Visual Studio 中的内置功能来构建模型,然后围绕它们创建数据库。创建控制器时,我可以选择数据上下文,它会为我创建实体框架类以及创建它的文件。在 Nuget 控制台中,我可以使用 Add-Migration 和 Update-Database 命令来创建数据库并在此过程中进行任何更改。
标签: c# asp.net-mvc-4 database-migration entity-framework-4.3