繁体   English   中英

计算属性和实体框架

[英]Computed Properties and Entity Framework

我有查询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);
}

感谢您的任何想法。

法布里奇奥

通常,最好的方法是有一个单独的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; }
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM