Search code examples
c#entity-frameworklinqlinq-to-entities

Linq SQL set property values to selected entity


Im using Code First Entity Framework and want to set property values of a selected entity within Linq. The problem is that I don't want to create a new entity object by setting every property manually.

I got this Linq:

var query = from myEntity in entities.MY_ENTITIES
            join joinEntity in entities.JOIN_ENTITIES on myEntity.JOIN_ID equals joinEntity.ID
            select new MY_ENTITY
            {
                ID = myEntity.Id,
                // all other myEntity properties that I want to avoid setting manually
                NotMappedProperty = joinEntity
            };

But instead of creating a new MY_ENTITY object I just want to set the NotMappedProperty of myEntity within the select.
Also I cannot map the two tables because my join is more complex and not really mappable.

Any idea on how to reduce the code instead of writing each property set manually? This can really blow up if you got an entity with many properties.


A solution would be to create a wrapping object, but that doesn't seem right:

public class MY_ENTITY_EXTENDED
{
    public MY_ENTITY MyEntity { get; set; }

    public JOIN_ENTITY JoinEntity { get; set; }
}

And in the Linq select:

// ...
select new MY_ENTITY_EXTENDED
{
    MyEntity = myEntity,
    JoinEntity = joinEntity
}

Solution

  • Daniel, something like this should work, where the joined entity is filled after returning the original set of entities:

    var list = new List<MY_ENTITY> ();
    
    var query = from myEntity in entities.MY_ENTITIES 
                select new MY_ENTITY
                {
                    ID = myEntity.Id,
                    // all other myEntity properties that I want to avoid setting manually
                    NotMappedProperty = null,  //    --> we will set this later
                    joinEntityIdToJoinTo = joinEntity.ID
                };;
    
    var joinedObjectsQuery = from myEntity in entities.JOIN_ENTITIES;
    
    foreach (var entity in query) 
    {
        list.Add( new MY_ENTITY {
            ID = entity.ID,
            NotMappedProperty = joinedObjectsQuery.Single(x=>xID == entity.joinEntityIdToJoinTo)
        })
    }