gpt4 book ai didi

c# - EF 代码优先的 RelationShip 错误

转载 作者:太空宇宙 更新时间:2023-11-03 16:05:09 26 4
gpt4 key购买 nike

我对这个程序结构和 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 的 ID 关系

你有什么建议吗?

这是 classDiagram 的链接: http://imageshack.us/a/img443/1854/jl98.png

非常感谢!

最佳答案

检查下面提到的链接。@John 对上述问题的解释如下。

EF does not support inheritance as you are attempting. It will work with abstract classes, but non-virtual properties. Generic Inhertiance is supported, but not from an abstract entity with a virtual property. You can have an abstract entity, but need non-virtual properties.

更多信息:G+ Solution

并且:Implementing Inheritance with the Entity Framework

关于c# - EF 代码优先的 RelationShip 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19786128/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com