使用 Entity Framework MVC ASP.NET 创建具有自定义类型的控制器时出错

Error Creating Controller With Custom Type using Entity Framework MVC ASP.NET

我正在尝试创建一个控制器,其中包含一个包含自定义类型的模型...

我有一个带有 ID 和类型 'Work' 的主 class,我在其中声明了三个属性,其中一个依赖于另外两个。然后我创建了一个 dbset 类型。我的映射属性不正确吗?

我收到以下错误: 所选代码生成器出现错误 运行:"Unable to retrieve metadata for 'Stack.Models.Work'"。 属性 总和不是 Math 类型上声明的 属性。使用 Ignore Method 或 NotMappedAttribute 数据注释验证 属性 没有被明确地从模型中排除。确保它是一个有效的原语 属性。

namespace stack.Models
{
public class Work
{
    [Key]
    public int ID { get; set; }

    public Work ()
    {
        this.Maths = new Math();
    }



    public Math Maths { get; set; }


}


[ComplexType]
public class Math
{

    public int first { get; set; }
    public int second { get; set; }
    public int sum
    {
        get
        {
            try
            {
                return first + second;
            }
            catch
            {
                return 0;
            }
        }

    }
}


public class WorkDBContext: DbContext
{
    public DbSet<Work> Working { get; set; }



    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

        modelBuilder.Entity<Work>()
                    .Property(c => c.Maths.first).IsRequired();

        modelBuilder.Entity<Work>()
                    .Property(c => c.Maths.second).IsRequired();

        modelBuilder.Entity<Work>()
                    .Property(c => c.Maths.sum).IsRequired();


        base.OnModelCreating(modelBuilder);
    }

}


}

Sum 不是简单类型(数据库中的列)它是数据函数(由其他属性计算),您不必将其存储在数据库中。

[ComplexType]
public class Math
{

    public int first { get; set; }
    public int second { get; set; }

    [NotMapped] 
    public int sum
    {
        get
        {
           return first + second;
        }
    }
}

删除这一行:

modelBuilder.Entity<Work>()
                    .Property(c => c.Maths.sum).IsRequired();