Linq SQL将属性值设置为所选实体

时间:2018-07-05 07:37:45

标签: c# entity-framework linq linq-to-entities

我使用Code First Entity Framework,并且想要在Linq中设置选定实体的属性值。问题是我不想通过手动设置每个属性来创建新的实体对象。

我得到了这个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
            };

但是我不想创建一个新的MY_ENTITY对象,而是只想在选择范围内设置myEntity的NotMappedProperty。
同样,我无法映射这两个表,因为我的联接更加复杂并且不是真正可映射的。

关于如何减少代码而不是手动编写每个属性集的任何想法?如果您拥有一个具有许多属性的实体,这真的会爆炸。


一种解决方案是创建一个包装对象,但这似乎不正确:

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

    public JOIN_ENTITY JoinEntity { get; set; }
}

然后在Linq中选择:

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

2 个答案:

答案 0 :(得分:0)

使用局部类将允许您扩展MY_ENTITY类。

例如

public partial class MY_ENTITY
{
   // db entity properties
}

public partial class MY_ENTITY
{
    public JOIN_ENTITY JoinEntity { get; set; }
}

答案 1 :(得分:0)

丹尼尔, 像这样的事情应该起作用,在返回原始实体集之后填充连接的实体:

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)
    })
}