c# - Entity Framework 查询中new Class Name和new Class Name()的区别

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

<分区>

我试图通过使用 Entity Framework 从数据库中获取一些值

我有疑问

Difference between new ClassName and new ClassName() in entity framewrok query

代码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() 对象的位置看到更改。

  • The both queries are working for me. but i don't know the differences between of code 1 and code 2 .

最佳答案

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

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

是这样的:

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

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

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

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

关于c# - Entity Framework 查询中new Class Name和new Class Name()的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30045859/

相关文章:

entity-framework - EF 5 代码优先字典映射

c# - 使用 C# 读取 TCP 流

c# - 按照添加顺序访问 DataGridView 行

java - Java中数组的内存使用开销的原因是什么?

performance - 与链表反转相关的一个想法

c# - 从 Entity Framework 中仅检索基类

asp.net - EF 4.1 N Tier ASP .Net 困惑

c# - TcpClient.GetStream().Read() 与 TcpClient.Client.Receive()

c# - 获取字符串中模式的匹配项

c# - 为什么函数调用要花这么多时间?