加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 17:36:43 所属栏目:百科 来源:网络整理
导读:我试图使用一个通用的EntityTypeConfiguration类来配置所有实体的主键,以便每个派生配置类不会重复.我的所有实体都实现了一个通用接口IEntity(它表示每个实体必须具有类型为int的Id属性). 我的配置基类如下所示: public class EntityConfigurationTEntity :
我试图使用一个通用的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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读