【问题标题】:Difference between new ClassName and new ClassName() in entity framewrok query [duplicate]实体框架查询中新类名和新类名()之间的区别[重复]
【发布时间】:2015-07-14 18:24:49
【问题描述】:

我尝试使用实体框架从数据库中获取一些值

我有疑问

实体框架查询中new ClassNamenew ClassName()的区别

代码 1

 dbContext.StatusTypes.Select(s => new StatusTypeModel() { StatusTypeId = 
 s.StatusTypeId, StatusTypeName = s.StatusTypeName }).ToList();

代码 2

dbContext.StatusTypes.Select(s => new StatusTypeModel { StatusTypeId =    
  s.StatusTypeId, StatusTypeName = s.StatusTypeName }).ToList();

您可以从我创建 new StatusTypeModelnew StatusTypeModel() 对象的位置看到更改。

  • 这两个查询都对我有用。但我不知道代码 1 和代码 2 之间的区别。

【问题讨论】:

标签: c# performance entity-framework class model-view-controller


【解决方案1】:

这与 EF 无关。这是 C# 语言功能。当你使用{ ... } 声明一个类的属性时,你不需要告诉一个类的空构造函数应该被调用。示例:

new StatusTypeModel() { StatusTypeId = s.StatusTypeId, ... }

完全一样是这样的:

new StatusTypeModel { StatusTypeId = s.StatusTypeId, ... }

性能没有区别。生成的 IL(中间语言)是相同的。

但是,如果您不声明属性,则必须像这样调用构造函数:

var x = new StatusTypeModel(); // brackets are mandatory
x.StatusTypeId = s.StatusTypeId;
...

【讨论】:

    猜你喜欢
    • 2011-09-15
    • 2013-08-19
    • 1970-01-01
    • 1970-01-01
    • 2011-07-02
    • 2012-12-09
    • 1970-01-01
    • 2015-07-16
    • 2016-01-19
    相关资源
    最近更新 更多