簡體   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