c# – 实体框架4.1 RC:Code First EntityTypeConfiguration继承问题

我试图使用一个通用的EntityTypeConfiguration类来配置所有实体的主键,以便每个派生配置类不会重复.我的所有实体都实现了一个通用接口IEntity(它表示每个实体必须具有类型为int的Id属性).

我的配置基类如下所示:

public class EntityConfiguration<TEntity> : EntityTypeConfiguration<TEntity>

    where TEntity : class,IEntity {

    public EntityConfiguration() {

        HasKey( e => e.Id );

        Property( e => e.Id ).HasDatabaseGeneratedOption( DatabaseGeneratedOption.Identity );

    }

}

然后每个实体都拥有自己的特定配置类,扩展这样一个如下所示:

public class CustomerConfiguration : EntityConfiguration<Customer> {

    public CustomerConfiguration() : base() {

        // Entity specific configuration here

    }

}

它编译得很好,但是我遇到的问题是,在运行时,当EF 4.1 RC尝试创建模型时,会得到以下异常:

System.InvalidOperationException was
unhandled Message=The key component
‘Id’ is not a declared property on
type ‘Customer’. Verify that it has
not been explicitly excluded from the
model and that it is a valid primitive
property. Source=EntityFramework

如果我将CustomerConfiguration类更改为从EntityTypeConfiguration< Customer>并重复主键配置,然后它工作正常,但我失去共享通用配置的能力(DRY主体是动机).

我在这里做错了吗?
>有没有另外一种方式来共享实体之间的通用配置?

以下参考其他类:

public interface IEntity {

    int Id { get; set; }

}

public class Customer : IEntity {

    public virtual int Id { get; set; }

    public virtual string name { get; set; }

}

谢谢!

解决方法

我不认为你需要经历这一切. EF 4.1代码首先使用大量的配置,通过这种方式,实体的Id属性被配置为主键.因此,通过在实体上实现IEntity接口,您将使用Id作为主键进行设置.

这是一个链接到ADO.NET团队博客,解释主要关键惯例如何工作 – Conventions for Code First

相关文章

项目中经常遇到CSV文件的读写需求,其中的难点主要是CSV文件...
简介 本文的初衷是希望帮助那些有其它平台视觉算法开发经验的...
这篇文章主要简单记录一下C#项目的dll文件管理方法,以便后期...
在C#中的使用JSON序列化及反序列化时,推荐使用Json.NET——...
事件总线是对发布-订阅模式的一种实现,是一种集中式事件处理...
通用翻译API的HTTPS 地址为https://fanyi-api.baidu.com/api...