【问题标题】:EF: using typeid map entity framework hierarchyEF:使用typeid映射实体框架层次结构
【发布时间】:2012-12-28 03:17:17
【问题描述】:

我不断收到此错误消息:

异常详情:MySql.Data.MySqlClient.MySqlException:“字段列表”中的未知列“Extent1.RuleType”

我的映射:

public abstract class AlertRule
{
    private DateTime? _updateDateTime = DateTime.Now;

    [Key]
    public int Id { get; set; }

    public int TemplateId { get; set; }
    public virtual AlertRuleTemplate Template { get; set; }

    public string RuleType
    {
        get
        {
            if (Template == null)
                return null;
            return Template.Name;
        }
    }
}
public class AlertOutageRule:AlertRule
{
    public virtual List<AlertRuleOutage> AlertRuleOutages { get; set; }
}
public class AlertMissingRule:AlertRule{}
public class AlertMetadataRule:AlertRule{}

        public DbSet<AlertRule> AlertRules { get; set; }

        modelBuilder.Entity<AlertRule>()
            .Map<AlertOutageRule>(m => m.Requires("RuleType").HasValue("NewsOutage"))
            .Map<AlertMetadataRule>(m => m.Requires("RuleType").HasValue("NewsMetadata"))
            .Map<AlertMissingRule>(m => m.Requires("RuleType").HasValue("NewsMissing"));
            //.Property(m => m.TemplateId).HasColumnType("int");

        modelBuilder.Entity<AlertRule>().ToTable("AlertRule");

【问题讨论】:

  • RuleType 没有设置器,因此您无法将其映射到持久数据库列,这是 EF 在检索对象时重新实现正确类型所必需的。
  • @MortenMertner 你的意思是这个属性应该在数据库中有一个对应列吗?
  • 是的;您必须添加 setter(以及列),或者删除映射中对该属性的所有引用。

标签: c# mysql entity-framework orm hierarchy


【解决方案1】:

public string RuleType 定义为只读(没有set{..})。

EF 不会将此属性映射到数据库。查看您的数据库架构,它将仅生成 2 列(Id,TemplateId)

【讨论】:

  • 但我不需要二传手也不希望它映射到数据库。有什么建议吗?
  • 那么你不能使用.Map&lt;AlertOutageRule&gt;(m =&gt; m.Requires("RuleType"),因为EF模型不能识别这个属性。改用数据注释或MetaDataAttributes
猜你喜欢
  • 2011-08-29
  • 2012-05-23
  • 2017-10-17
  • 2014-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-09
  • 1970-01-01
相关资源
最近更新 更多