我正在使用 MySQL .net 连接器 6.4.4.0 和 Entity Frame work 4.1 并尝试创建最基本的代码优先实现。
public class myDB: DbContext
{
public DbSet<Vote> Votes { get; set; }
}
我的模特
public class Vote
{
public Guid Id { get; set; }
public int Value { get; set; }
}
我的家庭 Controller
public class HomeController : Controller
{
myDB_db = new myDB();
public ActionResult Index()
{
var model = _db.Votes;
return View(model);
}
}
我的强类型 View (使用 List 脚手架)
@model IEnumerable<Namespace.Models.Vote>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.Value)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Value)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
@Html.ActionLink("Details", "Details", new { id=item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
</tr>
}
</table>
它在 mySQL 中创建具有所有正确属性的表“投票”。
但是,它会抛出这一行:
@foreach(模型中的变量项)
除了:
“表 'mydb.vote' 不存在”
编辑: 澄清一下,我实际上想要表格复数,并且似乎可以正确创建表格。我希望找出单数/复数差异的原因。 microsoft/Plural Sight/scott gu 的教程和视频都没有使用 mysql,所以我不得不想象 .netconnector 可能是罪魁祸首。我还想避免使用 [Table("Votes")] 属性。基本上,我希望尽可能多地提供“开箱即用”的解决方案。
edit2(一些更相关的代码): 当我删除这个...表无法一起创建。 但 View 抛出一个异常寻找“投票”而不是“投票”。 在 global.asax 中
protected void Application_Start()
{
Database.SetInitializer(new DropCreateDatabaseAlways<myDB>());
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
public class myDBInitializer : DropCreateDatabaseAlways<myDB>
{
protected override void Seed(myDBcontext)
{
base.Seed(context);
}
}
最佳答案
所以我放弃了尝试按照我认为应该这样做的方式去做,并一起删除了复数形式。我不确定,但我认为问题与 mysql .net 连接器对 EF 的支持有关。这就是我所做的。
首先,我的 ApplicationStart 方法中有一个错误:
//WRONG
//Database.SetInitializer(new DropCreateDatabaseAlways<myDB>());
Database.SetInitializer(new myDBInitializer());
其次,我不再调用原始代码中未列出的 OnModelCreating 基础实现,因为我只是按照 jgauffin 的建议实现了它:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//DONT DO THIS ANYMORE
//base.OnModelCreating(modelBuilder);
//modelBuilder.Entity<Vote>().ToTable("Votes")
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
第三,我在一些帖子中读到 MySQL .net 连接器不允许 EF 实际上创建数据库,所以我最初创建了空白数据库。连接器 6.4.4+ 似乎不再是这种情况,只要您的连接字符串的用户能够创建新数据库,如果最初不存在数据库,它会更好地工作。
有一次,我完成了以上所有操作,它似乎奏效了。所以现在我至少可以前进了。希望我们能在未来找出导致复数/单数差异的原因。
感谢大家的时间和精力。
关于c# - Entity Framework 创建复数表名,但 View 需要一个单数表名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7924758/