繁体   English   中英

如何在 C# 实体框架核心中使用 class 的构造函数,并将 class 作为字段?

[英]How do I use constructer for a class with a class as a field in C# Entity Framework Core?

我刚刚开始使用 C# 中的实体框架核心,我正在尝试设置一个 class 结构,其中一个 class 有一个字段是另一个 class 我发现,当类没有构造函数时,代码运行良好。 但是,当我按如下方式引入构造函数时:

    public class InterestEF
    {
        public InterestEF(string id, int numTimesInterestSelected, AdminEditEF lastEdit, ICollection<AdminEditEF> allEdits)
        {
            this.id = id;
            this.numTimesInterestSelected = numTimesInterestSelected;
            this.lastEdit = lastEdit;
            this.allEdits = allEdits;
        }

        [Key]
        public string id { get; set; }
        public int numTimesInterestSelected { get; set; }
        public AdminEditEF lastEdit { get; set; }
        public virtual ICollection<AdminEditEF> allEdits { get; set; }
    }

    public class AdminEditEF
    {
        public AdminEditEF(string id, string adminIdEditedBy, DateTime dateEdited, string changesMade, string reasonsForChanges, string idOfEditedEntity, EntityTypeEdited entityTypeEdited)
        {
            this.id = id;
            AdminIdEditedBy = adminIdEditedBy;
            this.dateEdited = dateEdited;
            this.changesMade = changesMade;
            this.reasonsForChanges = reasonsForChanges;
            this.idOfEditedEntity = idOfEditedEntity;
            this.entityTypeEdited = entityTypeEdited;
        }

        [Key]
        public string id { get; set; }
        public string AdminIdEditedBy { get; set; }
        public DateTime dateEdited { get; set; }
        public string changesMade { get; set; }
        public string reasonsForChanges { get; set; }
        public string idOfEditedEntity { get; set; }
        public EntityTypeEdited entityTypeEdited { get; set; }
    }

    public class MySQLEFContext : DbContext
    {
        public DbSet<AdminEditEF> AdminEdits { get; set; }

        public DbSet<InterestEF> interests { get; set; }

        public MySQLEFContext(DbContextOptions<MySQLEFContext> options): base(options) { }

    }

我收到以下错误:

System.InvalidOperationException: 'No suitable constructor found for entity type 'InterestEF'. The following constructors had parameters that could not be bound to properties of the entity type: cannot bind 'lastEdit' in 'InterestEF(string id, int numTimesInterestSelected, AdminEdit lastEdit)'.'

基本上,我只是想知道是否有可能拥有一个具有类作为字段的 class,它还具有一组带有参数的构造函数,我可以在代码中的其他地方调用?

任何帮助将不胜感激。 非常感谢您的阅读!

文档

  • EF Core 无法使用构造函数设置导航属性(例如上面的博客或帖子)。

因此,您需要一个如下所示的构造函数:

public InterestEF(string id, int numTimesInterestSelected)
{
    this.id = id;
    this.numTimesInterestSelected = numTimesInterestSelected;
}

或无参数的:

public InterestEF()
{
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM