Build string method using complex type Entity Framework ASP.NET C#

前端 未结 2 1842
梦毁少年i
梦毁少年i 2021-01-27 06:07

I had to use Entity Framework to equip an advanced search to my website application.

The model is generated from the database and has own entities but has some complex s

相关标签:
2条回答
  • 2021-01-27 06:23

    This is your problem, read up on c# anonymous types

    q => new
        {
            q.cFName,
            q.cLName,
            q.cSex,
            q.aId,
            q.cId,
            q.stars
       });
    

    Remove new, and if needed create a new type to hold this, adding back in new with

    new MyNewType {.. };
    

    THen use this type in your method

    0 讨论(0)
  • 2021-01-27 06:45

    To do this you need to build an external model with an IQueryable public method to returning data as IQueryable as following:

     public class customerComplex
    {
        public string cFName { get; set; }
        public string cLName { get; set; }
        public int cSex { get; set; }
        public string aId { get; set; }
        public string cId { get; set; }
        public int stars { get; set; }
    
        public IQueryable<customerComplex> GetValues()
        {
            return new List<customerComplex>().AsQueryable();
        }
    }
    

    Indeed, I don't know what the data-types are exactly of your data model, but we assume I guess right. know you can use the custom model customerComplex to get select data from your linq query as following
    :

    var queryFinal = query.Select(q => new customerComplex
                {
                    cId = q.cId,
                    cFName = q.cFName,
                    cLName = q.cLName,
                    cSex = q.cSex,
                    aId = q.aId,
                    stars = q.stars
                }).ToList();
    

    At last, you need to send the queryFinal to a function that you mentioned it. we assume you function is Customer_List(?). I defined this function in another class as following:

    public string Customer_List(IEnumerable<customerComplex> query)
    {
        string post = "";
        if(query.Count() > 0)
        {
            foreach (var item in query)
            {
                string name = item.cFName + " " + item.cLName;
                post += "<p>" + name + "</p>";
            }
        }
        return post;
    }
    

    Now, You can call Customer_List() and sent the queryFinal as folloing code:

    string post = cls.Customer_List(queryFinal.AsEnumerable());
    
    0 讨论(0)
提交回复
热议问题