实体framewrok查询中新ClassName和新ClassName()之间的区别

Ram*_*ran 5 c# model-view-controller performance entity-framework class

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

我有一个疑问

实体framewrok查询之间new ClassName和之间的new ClassName()区别

代码1

 dbContext.StatusTypes.Select(s => new StatusTypeModel() { StatusTypeId = 
 s.StatusTypeId, StatusTypeName = s.StatusTypeName }).ToList();
Run Code Online (Sandbox Code Playgroud)

代码2

dbContext.StatusTypes.Select(s => new StatusTypeModel { StatusTypeId =    
  s.StatusTypeId, StatusTypeName = s.StatusTypeName }).ToList();
Run Code Online (Sandbox Code Playgroud)

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

  • 这两个查询都适合我.但我不知道代码1和代码2之间的区别.

Qua*_*yst 5

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

new StatusTypeModel() { StatusTypeId = s.StatusTypeId, ... }
Run Code Online (Sandbox Code Playgroud)

这是完全一样的:

new StatusTypeModel { StatusTypeId = s.StatusTypeId, ... }
Run Code Online (Sandbox Code Playgroud)

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

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

var x = new StatusTypeModel(); // brackets are mandatory
x.StatusTypeId = s.StatusTypeId;
...
Run Code Online (Sandbox Code Playgroud)