Return anonymous type results?

后端 未结 16 1105
梦毁少年i
梦毁少年i 2020-11-22 03:01

Using the simple example below, what is the best way to return results from multiple tables using Linq to SQL?

Say I have two tables:

Dogs:   Name, A         


        
16条回答
  •  隐瞒了意图╮
    2020-11-22 03:48

    If the main idea is to make the SQL select statement sent to the Database server have only the required fields, and not all the Entity fields, then u can do this:

    public class Class1
    {
        public IList getCarsByProjectionOnSmallNumberOfProperties()
        {
    
            try
            {
                //Get the SQL Context:
                CompanyPossessionsDAL.POCOContext.CompanyPossessionsContext dbContext 
                    = new CompanyPossessionsDAL.POCOContext.CompanyPossessionsContext();
    
                //Specify the Context of your main entity e.g. Car:
                var oDBQuery = dbContext.Set();
    
                //Project on some of its fields, so the created select statment that is
                // sent to the database server, will have only the required fields By making a new anonymouse type
                var queryProjectedOnSmallSetOfProperties 
                    = from x in oDBQuery
                        select new
                        {
                            x.carNo,
                            x.eName,
                            x.aName
                        };
    
                //Convert the anonymouse type back to the main entity e.g. Car
                var queryConvertAnonymousToOriginal 
                    = from x in queryProjectedOnSmallSetOfProperties
                        select new Car
                        {
                            carNo = x.carNo,
                            eName = x.eName,
                            aName = x.aName
                        };
    
                //return the IList that is wanted
                var lst = queryConvertAnonymousToOriginal.ToList();
                return lst;
    
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
                throw;
            }
        }
    }
    

提交回复
热议问题