Gio*_*iox 5 c# entity-framework
我已将旧应用程序从 EF6 DB First 迁移到从现有数据库手动生成的上下文,并始终在 ASP.NET 4.7 上使用 EF6。
上下文定义如下:
namespace DataModel
{
using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
public partial class MyEntities : DbContext
{
public MyEntities()
: base("name=MyEntities")
{
}
public virtual DbSet<Country> Countries { get; set; }
public virtual DbSet<SomeNameSpace.Report> RE_Reports { get; set; }
}
}
Run Code Online (Sandbox Code Playgroud)
类实体Report定义如下:
namespace DataModel
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
namespace SomeNameSpace
{
public partial class Report
{
[Key]
public int ReportID { get; set; }
[StringLength(1024)]
public string Title { get; set; }
}
}
}
Run Code Online (Sandbox Code Playgroud)
编译时一切正常,应用程序成功构建。当我在第一次访问报告实体时运行它时,我收到以下错误:
对象名称“dbo.Reports”无效
因此,实体框架在 SQL 查询中将表名称转换为Reports复数形式的实体名称,而不是转换为RE_Reports数据库表的实际名称。
为什么?
请注意,使用其他实体(例如国家/地区)的查询在运行时也可以正常工作。
唯一的区别是我添加到报告表中的附加命名空间。
因此,实体框架在 SQL 查询中将表名称转换为 Reports(实体的复数名称),而不是转换为 RE_Reports(数据库表的实际名称)。
为什么?
因为它是Convention实体框架中的。
实体框架提供三个选项将实体名称映射到表名称:
使用流畅的方法OnModelCreating:
modelBuilder.Entity<Report>().ToTable("RE_Reports");
在实体类上使用属性(如Guru Stron答案中提到的):
[Table("RE_Reports")]
使用Convention:
如果开发人员未应用选项 1 和 2,EF 默认情况下会将表名称推断为实体名称的复数形式(您的情况)
| 归档时间: |
|
| 查看次数: |
8572 次 |
| 最近记录: |