等效于Entity Framework中的“ SELECT NULL AS ColumnName”

时间:2019-03-20 15:40:27

标签: c# entity-framework linq tsql

我有一种情况要求将某些列值返回为NULL。

我知道您可以使用投影来限制返回或选择的列,但这不是我们想要的。

作为一个简化示例,假设我有一个5列表,称为dbo.Person

+------+---------+-----+------------------------------------------------------------------------+------------------------------------------------+
| Name | Surname | Age |                                 About                                  |                     Likes                      |
+------+---------+-----+------------------------------------------------------------------------+------------------------------------------------+
| Bob  | Doe     |  22 | Grew up in no-man's land. Very strong. Also known as Bobby             | Burgers, Taking care of fish, kissing dolphins |
| Jane | Doe     |  21 | Grew up on the space station. Supremely intelligent. Also known as Jay | Icecream, Pug named Star Freak, Petting lions  |
| John | Doe     |  25 | Grew up in a whale. Can sing in sonar. Also known as Unknown           | Krill, Box Jellyfish, snacking on sea weed.    |
+------+---------+-----+------------------------------------------------------------------------+------------------------------------------------+

我有一个与上表相关的实体类

[Table("Person")]
public class Person
{
    public string Name {get; set}

    public string Surname {get; set;}

    public string Age {get; set;}

    public string About {get; set;}

    public string Likes {get; set;}
}

我已经定义了与数据库相对应的上下文:PeopleContext : DbContext

我在public DbSet<Person> Person{ set; get;}中定义了PeopleContext

假设其他所有设置都可以正常工作,

无需投影到Person以外的其他对象,如何编写与以下内容等效的Entity Framework查询?

SELECT
   Name,
   Surname,
   Age,
   NULL AS About,
   NULL AS Likes 
FROM dbo.Person

1 个答案:

答案 0 :(得分:0)

这是ViewModel / Consumer问题,不是实体问题。实体应始终反映实际数据状态或预期数据状态。

如果您打算清除“关于”和“喜欢”,则:

var person = context.People.Single(x => x.PersonId == personId);
person.About = null;
person.Likes = null;

当/如果您在上下文中调用SaveChanges(),这些预期的更改将保留下来。如果您不打算保存更改,则这是一个危险的选择,因为尽管更改可能在今天生效,但明天可能是有人提出要求通过上下文保存某些内容的日子。

如果您要使用没有“关于”或“喜欢”值的“人”,则:

var personViewModel = context.People
    .Where(x => x.PersonId == personId)
    .Select(x => new PersonViewModel
    {
        Name = x.Name,
        Surname = x.Surname,
        Age = x.Age
    }).Single();

如果需要,视图模型可以包含“关于”和“喜欢”值,默认为#null。

或者,如果您只是想就地使用该数据,而又不撤回该人的“关于”和“喜欢”的额外细节,则可以使用匿名类型:

var personDetails = context.People
    .Where(x => x.PersonId == personId)
    .Select(x => new 
    {
        x.Name,
        x.Surname,
        x.Age
    }).Single();