实体框架选择具有多对多关系且不是数字的特定于和的列子表

本文关键字:于和的 和的 数字 选择 框架 关系 实体 | 更新日期: 2023-09-27 18:23:58

我有这个类

        using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.ComponentModel.DataAnnotations;
    namespace IVF_EHR.Models
    {
        public class SemenProcess
        {
            public Guid SemenProcessID { get; set; }
            public virtual List<CollectionMethod> CollectionMethods { get; set; }
            public SemenProcess()
            {
                SemenProcessID = Guid.NewGuid();
                CollectionMethods = new List<CollectionMethod>();
            }
        }
    }

正如你所看到的,这个类有关系宽度这个类

            using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using DevExpress.Web.ASPxEditors;
    namespace IVF_EHR.Models
    {
        public class CollectionMethod
        {
            [Key]
            public int CollectionMethodID { get; set; }
            [Required]
            [MaxLength(50)]
            public string Title { get; set; }
            public virtual List<SemenProcess> SemenProcesss { get; set; }
            public CollectionMethod()
            {
                CollectionMethodID = 0;
                Title = "";
                SemenProcesss = new List<SemenProcess>();
            }
        }
    }

这两类之间的关系是多对多的。我需要写一个性能良好的单linq查询来完成这个

select dbo.GetWokeTitle(s.SemenProcessID)[woleTitle] , * from [SemenProcesses] [s] 

CCD_ 1就是这样的

    CREATE FUNCTION GetWokeTitle
    (
        @SemenProcessID uniqueidentifier 
    )
    RETURNS nvarchar(max)
    AS
    BEGIN
        declare @result nvarchar(max)
        set @result = '';
        select @result = @result + title  from [SemenProcessCollectionMethods] [sc] inner join [CollectionMethods] [c] on c.[CollectionMethodID]=sc.[CollectionMethod_CollectionMethodID]
        where sc.SemenProcess_SemenProcessID=@SemenProcessID
        -- Return the result of the function
        RETURN @result
    END
    GO

我使用ADO.NET实体框架,我需要编写一个linq查询,该查询与上面的SQL代码相同。还有一件事由于性能问题,我无法执行.ToList(),我需要在不执行该查询的情况下生成一个查询。实际上,我有一个控件,该控件使用查询而不是对象列表,并且该控件自己执行查询。我可以创建视图并在实体中使用该视图,但我想要一些其他东西,也就是最后一种方式

实体框架选择具有多对多关系且不是数字的特定于和的列子表

以下是我的建议。创建这样的ViewModel:

public class SemenProcessViewModel
{
  public string WokeTitle { get; set; }
  public SemenProcess SemenProcess { get; set; }
}

然后,您的linq查询将是这样的:

var semenProcessViewModel = db.SemenProcesses
   .Where(s => s.SemenProcessID == semenProcessID).ToList()
   .Select(s => new SemenProcessViewModel {
       SemenProcess = s,
       WokeTitle = string.Join("", s.CollectionMethods.Select(c => c.Title))
   }).SingleOrDefault();