实体框架查询中new Class Name和new Class Name()的区别

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

我试图通过使用 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# 语言功能。当您使用 { ... } 声明 class 的属性时,您无需告知应调用 class 的空构造函数。示例:

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

完全一样是这样的:

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

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

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

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