Linq to SQL DTOs and composite objects

后端 未结 3 1032
栀梦
栀梦 2021-02-10 16:29

I am using a similar approach to others in keeping my LINQ objects in my LINQ data provider and returning an IQueryable to allow filtering etc. This works fine for filtering a

3条回答
  •  时光说笑
    2021-02-10 17:08

    Linq2SQL does only understand the designer-generated objects. Well, that's not entirely true, but close enough.

    So when you write Linq queries agains Linq2SQL objects, the query will be converted to valid SQL when the query is actually executed, not when it's written. Since your DTO objects are not Linq2SQL objects, Linq2SQL will not know how to create the proper SQL.

    If you want to keep your separation this way, you have to find a way to execute your queries with only Linq2SQL objects involved and only map the result to your DTOs.

    Maybe you could rewrite your query method to:

    Update: Parameter must be of type Expression<>, and there's no need to return an IQueryable<>. Thanks to Freddy for pointing out.

    public IEnumerable FindPositions(Expression> criteria)
    {
        return from p in coreDB.Positions
               where criteria.Invoke(p)
               select new DTO.Position
                          {
                              User = new DTO.User(p.User.id, p.User.username, p.User.firstName, p.User.lastName,
                                           p.User.email, p.User.isActive),
                              Role = new DTO.Role(p.Role.id, p.Role.name, p.Role.isActive),
                              OrgUnit = new DTO.OrgUnit(p.OrgUnit.id, p.OrgUnit.name, p.OrgUnit.isActive)
                          };
    }
    

提交回复
热议问题