2 域类中的构造函数

我正在接受培训并查看一些网络应用程序的代码。我们在我们的组织中使用 MVC,我不确定为什么我们需要 2 个这样的构造函数,请解释一下,以便我可以更好地了解它。谢谢。


namespace ddc.Core.Domain

{

    public class Request : Entity

    {

        public Request()

        {


        }


        public Request(int buildingId, int adId, DateTime eventDate, DateTime eventStart, DateTime eventEnd, DateTime? timeOfApproval)

        {

            this.BuildingId = buildingId;

            this.AdId = adId;

            this.EventDate = eventDate;

            this.StartTime = eventStart;

            this.PowerNeed = powerNeed;

            this.EventDescription = eventDescription;

            this.EnteredBy = enteredBy;

            this.EnteredOn = enteredOn;

            this.TimeOfApproval = timeOfApproval;

        }


        public virtual int BuildingId { get; set; }

        public virtual int AdId { get; set; }

        public virtual DateTime EventDate { get; set; }

        public virtual DateTime StartTime { get; set; }

        public virtual DateTime EndTime { get; set; }

        public virtual DateTime? TimeOfApproval { get; set; }

    }

}


繁星淼淼
浏览 133回答 3
3回答

肥皂起泡泡

具有大量参数的构造函数允许某人实例化一个对象并在一次构造函数调用中设置所有属性,这通常非常方便:var request = new Request(buildingId, adId, eventDate, eventStart, eventEnd, timeOfApproval);但是,一旦定义了自己的构造函数,就不再有自动生成的默认构造函数(它允许您创建不带任何参数的对象),因此必须手动定义。var request = new Request();// Later...request.BuildingId = buildingId;request.AdId = adId;request.EventDate = eventDate;//...etc.因此这个类有两个构造函数。

守候你守候我

如果您使用实体框架,则必须有一个无参数构造函数。当实体框架从数据库查询映射到实体时,使用默认构造函数实例化实体的新实例,以使用从数据库检索的数据填充它。因此,当您拥有第二个时,您可以创建一个实例并设置所有属性new Request(buildingId, adId, ...);您需要为 EF 添加第一个(无参数构造函数)。它允许创建一个实例并仅设置您需要的属性(或不设置任何属性),因为所有属性都有公共设置器new Request{    BuildingId =  buildingId,    AdId =  adId,    ...}

湖上湖

无参数构造函数应该是因为实体框架需要它从数据库创建对象。我建议为此使用内部范围。
打开App,查看更多内容
随时随地看视频慕课网APP