簡體   English   中英

EF代碼優先的RelationShip錯誤

[英]RelationShip error on EF code-first

我對這個程序結構和EF 6有一個奇怪的問題。

public abstract class Operand
{
    public virtual int Id
    {
        get;
        set;
    }
}

public class Formula : Operand
{
    public Operand Operand1
    {
        get;
        set;
    }

    public Operand Operand2
    {
        get;
        set;
    }

    public String Operator
    {
        get;
        set;
    }


    public override int Id
    {
        get;
        set;
    }
}

public class OperandValue<T> : Operand
{
    public T Value
    {
        get;
        set;
    }


    public override int Id
    {
        get;
        set;
    }
}

public class OperandInt : OperandValue<int>
{
}

public class ModelEntity : DbContext
{
    public ModelEntity()
        : base("MyCnxString")
    {
        this.Configuration.LazyLoadingEnabled = true;
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

        modelBuilder.Types<Formula>()
        .Configure(c => c.ToTable(c.ClrType.Name));

        modelBuilder.Types<OperandInt>()
        .Configure(c => c.ToTable(c.ClrType.Name));
    }

    public DbSet<Formula> Formula { get; set; }
    public DbSet<OperandInt> OperandValue { get; set; }

}

和我的測試程序:

public class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Starting...");


        var migration = new TestEntity2.Migrations.Configuration();
        migration.AutomaticMigrationsEnabled = true;
        migration.AutomaticMigrationDataLossAllowed = true;

        var migrator = new System.Data.Entity.Migrations.DbMigrator(migration);
        migrator.Update();


        using (ModelEntity db = new ModelEntity())
        {
            OperandInt opValue1 = new OperandInt() { Value = 3 };
            db.OperandValue.Add(opValue1);

            OperandInt opValue2 = new OperandInt() { Value = 4 };
            db.OperandValue.Add(opValue2);

            Formula formula = new Formula() { Operand1 = opValue1, Operand2 = opValue2, Operator = "*" };
            db.Formula.Add(formula);


            db.SaveChanges();

            Console.WriteLine("Ended !");
            Console.ReadLine();
        }
    }
}

當我執行該程序時,我得到以下錯誤消息:

關系“ Formula_Operand1”與概念模型中定義的任何關系都不匹配。

問題是由於GenericType繼承,“公式”未找到Operand1和Operand2 Ids關系

你有什么建議嗎?

這是classDiagram的鏈接: http ://imageshack.us/a/img443/1854/jl98.png

非常感謝 !

檢查下面提到的鏈接。@ John關於上述問題的解釋如下。

EF在嘗試時不支持繼承。 它將與抽象類一起使用,但與非虛擬屬性一起使用。 支持通用繼承,但不支持具有虛擬屬性的抽象實體。 您可以具有抽象實體,但需要非虛擬屬性。

有關更多信息: G +解決方案

並且: 使用實體框架實現繼承

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM