[c#]将 LINQ 查询的结果转换为列表的自定义模型

标签: sql Asp.net Linq C#
发布时间: 2017/2/25 3:45:09
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

大家晚上好。

我有 LINQ to SQL 查询结果,并且我想要这个结果的转换的列表的自定义模型类

这类模型︰

public class Beneficiary
    {
        public int BeneficiaryId { get; set; }

        [Required]
        public string FirstName { get; set; }
        [Required]
        public string LastName { get; set; }

        public DateTime? CreatedAt { get; set; }

        [Column(TypeName = "date")]
        public DateTime? BithDate { get; set; }

        public int? CommunityId { get; set; }
        public virtual Community Community { get; set; }

        [Required]
        public string Gender { get; set; }


        public string IdNumber { get; set; }

        [Required]
        [StringLength(50)]
        public string AppName { get; set; }

        [StringLength(50)]
        public string BeneficiaryNumber { get; set; }

        public int CompanyId { get; set; }
        public virtual Company Company { get; set; }

        public virtual ICollection<BeneficiaryProject> BeneficiaryProjects { get; set; }

        public virtual ICollection<Card> Cards { get; set; }

        public virtual ICollection<Invoice> Invoices { get; set; }
    }

和这里是我使用的查询︰

var list  = (from B in db.Beneficiaries
                               join ben in db.BeneficiaryProjects on B.BeneficiaryId equals ben.BeneficiaryId
                               where (ben.CardNeeded == true && ben.ProjectId == temp.ProjectId)
                               select new Beneficiary()
                               {
                                   BeneficiaryId = B.BeneficiaryId,
                                   FirstName = B.FirstName,
                                   LastName = B.LastName,
                                   IdNumber = B.IdNumber,
                                   Gender = B.Gender
                               });

成功地执行上述查询,但当我转换 var list 到列表中的 Beneficiary 如下︰

            List<Beneficiary> list1 = list.ToList<Beneficiary>();

但我得到了以下异常︰

 An exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll but was not handled in user code

Additional information: The entity or complex type 'E_Voucher.Models.Beneficiary' cannot be constructed in a LINQ to Entities query.

解决方法 1:

为什么您收到此错误的原因 (在这条线:)

List<Beneficiary> list1 = list.ToList<Beneficiary>();

是你正在向一个 Linq 查询变量的转换的列表。

你真正需要做的所有是以下内容︰

List<Beneficiary> list1 = list.ToList();

你有为 temp 的查询。ProjectID:

var projects = db.Projects.Where(p => p.ContractId == id); foreach (var temp in projects)

应类似于︰

int ProjectId = (from P in db.Projects where P.ContractId == id select P.ProjectId).FirstOrDefault();

采取这个值,然后放入你的下一个查询︰

... where (ben.CardNeeded == true && ben.ProjectId == ProjectId)
官方微信
官方QQ群
31647020