微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/csharp/96367.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐