简体   繁体   中英

Use projection to fill not mapped types in EF

We have a specific struct called Measure and we'd like to use this type instead of the database field type eg double.

So we have an entity:

public class MyEnity
{
   public int MyValue { get; set; }
}

And we have a transfer object: public class MyDto { public Measure MyMeasureValue{ get; set; } }

If the property type would match, we just can fill our dto's per projection:

enities.Select(i => new MyDto { MyMeasureValue = new Measure(i.MyValue, _unitsService.GetUnit("km")) });

But since EF does not support such statements, we have to refill this, or load the whole entity:

entities.Select(i => new { MyValue = i.MyValue })
        .AsEnumerable()
        .Select(i => new MyDto { MyMeasureValue = new Measure(i.MyValue, _unitsService.GetUnit("km")) } );

We want to avoid this looping several times in the refill process, especially because there are a lot of properties to fill. Is there a way we can go with the first statement and teach EF to execute the Measure creation? (eg interception etc.)

PS. It is not an option to create a EF complex type and map it!

Thanks Enyra

You may use complex types while fetching some properties of the entity using Linq-Entity. For instance;

Model1Container container = new Model1Container();
var temp = from o in container.MasterSet
           select new
                  {
                       x = o.LastModifiedBy,
                       y = o.LastModifiedDate
                  };

By the way, instead of mapping DTOS by hand, it is better to use autommaper. It has the functionality to map matching proper names without explicity declaring.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM