【发布时间】:2014-08-21 04:40:17
【问题描述】:
我在使用 EF 时遇到问题。 我有以下情况:
从这个数据库架构中,我想通过合并表数据来生成以下实体:
// Purchases
public class Purchase
{
//Fields related to Purchases
public int IdPurchase { get; set; }
public string CodPurchase { get; set; }
public int IdCustomer { get; set; }
public decimal Total { get; set; }
//Fields related to Customers table
public string CodCustomer { get; protected set; }
public string CompanyTitle { get; protected set; }
public string CodType { get; protected set; }
//Fields related to CustomersType table
public string DescrType { get; protected set; }
}
如您所见,在我的上下文中,我不希望每个表有 3 个单独的实体。我想要一个与所有表相关的字段。客户和客户类型表的所有字段都必须是只读的(因此我已将相关设置器设置为受保护),其他字段必须是可编辑的,以便 EF 可以跟踪更改。特别是,我希望能够更改“IdCustomer”字段并让 EF 通过交叉表选择自动更新“CodCustomer”、“CompanyTitle”、“DescrType”......等等。
为此,我编写了这个配置类:
internal class PurchaseConfiguration : EntityTypeConfiguration<Purchase>
{
public PurchaseConfiguration(string schema = "dbo")
{
ToTable(schema + ".Purchases");
HasKey(x => x.IdPurchase);
Property(x => x.IdPurchase).HasColumnName("IdPurchase").IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(x => x.IdCustomer).HasColumnName("IdCustomer").IsRequired();
Property(x => x.Total).HasColumnName("Total").IsRequired().HasPrecision(19, 4);
Map(mc =>
{
mc.Properties(n => new
{
n.CodCustomer,
n.CompanyTitle,
n.CodType
});
mc.ToTable("Customers");
});
Map(mc =>
{
mc.Properties(n => new
{
n.DescrType,
});
mc.ToTable("CustomersType");
});
}
}
我已经对其进行了测试,但它没有按预期工作。我总是收到这条消息:
“购买”类型的属性只能映射一次。非关键 属性“CodCustomer”被多次映射。确保 Properties 方法只指定每个非键属性一次。
也许有什么问题或者我忘记了一些东西(例如我不知道在哪里指定它们的 Map 的连接字段)。 我怎样才能以正确的方式完成这项任务? 我不想在我的上下文中使用“Customers”和“CustomersType”DBSet。 有办法避免吗?
我什至想在“IdCustomer”设置器中添加一个自定义查询来手动更新“Customers”和“CustomersType”相关字段,但我不想这样做有两个原因:
- 我没有任何 DbConnection 可用于“Purchases”类,因此我无法创建 DbCommand 来从 DB 读取数据。
- 我希望实体类是持久无知的
- EF 似乎是一个强大的工具,可以做这些事情,我不想通过编写自定义程序来重新发明轮子。
我已经上传了示例 C# 源代码和表 CREATE 脚本 (MS SQLServer) here。 所有实体都由“EF 反向 POCO 生成器”T4 模板自动生成(T4 模板被禁用,激活它设置 CustomTool = TextTemplatingFileGenerator)。 不要忘记更新 app.config 中的 ConnectionString。
提前致谢。
【问题讨论】:
标签: c# entity-framework orm mapping entity