Answer the question
In order to leave comments, you need to log in
How to add data to the database when creating?
Hello, there are 2 models:
public class Service : EntityBase
{
public Guid Id { get; set; }
public override string H1 { get; set; }
public virtual Category Category { get; set; }
}
[Owned]
public class Category : EntityBase
{
public Guid Id { get; set; }
}
public DbSet<Entities.Service> Services { get; set; }
public DbSet<Entities.Category> Categories { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<Entities.Service>(b =>
{
b.HasData(new Entities.Service
{
Id = new Guid("666599D8-EAC4-4F43-9F15-B7063C583B76"),
Url = "usluga-1",
H1 = "Услуга 1"
});
b.OwnsOne(x => x.Category).HasData(new Category
{
Id = new Guid("309035C6-9489-41CA-A395-717243880814"),
Url = "default",
H1 = "По умолчанию",
});
});
}
Answer the question
In order to leave comments, you need to log in
It was necessary to create an object of an anonymous type so that a value could be written in the CategoryId, while the CategoryId field itself did not need to be created, the model remains the same
builder.Entity<Category>().HasData(new Entities.Category
{
Id = new Guid("309035C6-9489-41CA-A395-717243880814"),
Url = "default",
H1 = "По умолчанию"
});
builder.Entity<Entities.Service>().HasData(new
{
Id = new Guid("666599D8-EAC4-4F43-9F15-B7063C583B76"),
Url = "usluga-1",
H1 = "Услуга 1",
CategoryId = new Guid("309035C6-9489-41CA-A395-717243880814")
});
The connection is indicated either through attributes or through the fluent api, this is easily googled. You have a one-to-many relationship, one service has many categories, so EF will add the ServiceId field to the Category table when creating tables. Apparently, you need to explicitly specify the service id for the data connection there, for this you need to add this field to the Category model.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question