Search code examples
linq-to-sql.net-4.0domain-driven-designexpression-trees

Will manual Linq-To-Sql mapping with Expressions work?


I have this problem: enter image description here

The Vehicle type derives from the EntityObject type which has the property "ID".

I think i get why L2S can't translate this into SQL- it does not know that the WHERE clause should include WHERE VehicleId == value. VehicleId btw is the PK on the table, whereas the property in the object model, as above, is "ID".

Can I even win on this with an Expression tree? Because it seems easy enough to create an Expression to pass to the SingleOrDefault method but will L2S still fail to translate it?

I'm trying to be DDD friendly so I don't want to decorate my domain model objects with ColumnAttributes etc. I am happy however to customize my L2S dbml file and add Expression helpers/whatever in my "data layer" in the hope of keeping this ORM-business far from my domain model.

Update:

I'm not using the object initialization syntax in my select statement. Like this:

private IQueryable<Vehicle> Vehicles() 
{
    return from vehicle in _dc
        select new Vehicle() { ID = vehicle.VehicleId };
}

I'm actually using a constructor and from what I've read this will cause the above problem. This is what I'm doing:

private IQueryable<Vehicle> Vehicles() 
{
    return from vehicle in _dc
        select new Vehicle(vehicle.VehicleId);
}

I understand that L2S can't translate the expression tree from the screen grab above because it does not know the mappings which it would usually infer from the object initialization syntax. How can I get around this? Do I need to build a Expression with the attribute bindings?


Solution

  • I have decided that this is not possible from further experience.

    L2S simply can not create the correct WHERE clause when a parameterized ctor is used in the mapping projection. It's the initializer syntax in conventional L2S mapping projections which gives L2S the context it needs.

    Short answer - use NHibernate.