计算属性和实体框架

时间:2018-08-28 10:59:42

标签: c# linq model-view-controller

查询linq有问题。

我有这节课:

public abstract class Subject : IValidatableObject
{
    public abstract string FullName { get; }

    public abstract SubjectType SubjectType { get; }

    public string FiscalIdentifier => String.IsNullOrEmpty(VatNumber) ? FiscalCode : VatNumber;
}

[Table("Person")]
public partial class Person : Subject
{
    public override string FullName => FirstName + " " + LastName;

    public override SubjectType SubjectType => SubjectType.Person;

    public string FirstName { get; set; }

    public string LastName { get; set; }
}


[Table("Corporation")]
public partial class Corporation : Subject
{
    public override string FullName => Name;

    public override SubjectType SubjectType => SubjectType.Corporation;

    public string Name { get; set; }
}

午餐时查询

 IQuerable<Subject> result = GetList()
   .OrderBy(s => s.FullName)
   .Skip(start)
   .Take(length)
   .ToList();

框架显示以下错误:“仅支持初始化程序,实体成员和实体导航属性”

我也曾尝试使用这些库,但午餐例外:

DelegateDecompiler :“无法将类型'OneData.DataModel.Subject'强制转换为类型'OneData.DataModel.Person'。 LINQ to Entities仅支持强制转换EDM基本类型或枚举类型。

public abstract class Subject : IValidatableObject
{
    [Computed]
    public abstract string FullName { get; }

    [Computed]
    public abstract SubjectType SubjectType { get; }

    [Computed]
    public string FiscalIdentifier => String.IsNullOrEmpty(VatNumber) ? FiscalCode : VatNumber;
}

 IQuerable<Subject> result = GetList()
   .OrderBy(s => s.FullName)
   .Skip(start)
   .Take(length)
   .Decompile()
   .ToList();

Linq.Translations :已经添加了具有相同键的项目。

public partial class Person : Subject
{
    private static readonly CompiledExpression<Person, string> FullNameExpression
        = DefaultTranslationOf<Person>.Property(e => e.FullName).Is(e => e.FirstName + " " + e.LastName);

    public override string FullName => FullNameExpression.Evaluate(this);
}


public partial class Corporation : Subject
{
    private static readonly CompiledExpression<Corporation, string> FullNameExpression
        = DefaultTranslationOf<Corporation>.Property(e => e.FullName).Is(e => e.Name);

    public override string FullName => FullNameExpression.Evaluate(this);
}

感谢任何想法。

Fabrizio

1 个答案:

答案 0 :(得分:0)

通常,最好的方法是有一个单独的DTO类,仅用于与数据库通信,这些类将仅具有要保留在数据库中的属性。在您的业务逻辑中,您使用不同的类。这看似重复,但使您的代码更加灵活和可维护。

// Use for database
[Table("Person")]
public class PersonDto
{
    public string FirstName { get; set; }

    public string LastName { get; set; }
}

// Use in business logic 
public partial class Person : Subject
{
    public override string FullName => FirstName + " " + LastName;

    public override SubjectType SubjectType => SubjectType.Person;

    public string FirstName { get; set; }

    public string LastName { get; set; }
 }