Я только начинаю работать с Entity Framework Core в С# и пытаюсь настроить структуру класса, в которой один класс имеет поле, являющееся другим классом. Я обнаружил, что когда у классов нет конструкторов, код работает нормально. Однако, когда я ввожу конструктор следующим образом:
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)'.'
По сути, мне просто интересно, возможно ли иметь класс, в котором есть классы в качестве полей, который также имеет набор конструкторов с параметрами, которые я могу вызывать в другом месте кода?
Любая помощь будет принята с благодарностью. Большое спасибо за чтение!
Однако можно ли добавить конструктор с параметрами? Я хочу иметь набор конструкторов, которые принимают разные параметры в зависимости от того, что я хочу делать с классом. Я ценю, что вы так быстро ответили! Спасибо!
learn.microsoft.com/en-us/ef/core/modeling/constructors Вскоре у вас может быть столько конструкторов, сколько вы пожелаете для собственных нужд, но по крайней мере один, даже частный, будет использоваться EF Core, когда материализующая сущность, возвращающая запросы.
ой! в этом есть смысл! большое спасибо!
Из документов:
- EF Core не может задавать свойства навигации (например, «Блог» или «Сообщения» выше) с помощью конструктора.
Итак, вам понадобится конструктор, который выглядит так:
public InterestEF(string id, int numTimesInterestSelected)
{
this.id = id;
this.numTimesInterestSelected = numTimesInterestSelected;
}
Или без параметров:
public InterestEF()
{
}
Вы также можете просто добавить еще один конструктор без параметров.