Cześć, stworzyłem sobie klasę instytucja która ma listę klientów wygenerowałem tabele za pomocą Entity Framework.
instytucja.cs:
public class Institution
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual List<Customer> Customers { get; set; }
}
Klient:
public int Id { get; set; }
public string Name { get; set; }
public string SecoundName { get; set; }
public string LastName { get; set; }
public string PasswordHash { get; set; }
public int InstitutionId { get; set; }
public virtual Institution Institution { get; set; }
I teraz chciałbym zrobić prosta tabele z Rolami dla klientów:
public class Role
{
public int Id { get; set; }
public string Name { get; set; }
}
Jak mogę zrobić relacje między nimi? Próbowałem do klasy klienta dodać:
public int Id { get; set; }
public string Name { get; set; }
public string SecoundName { get; set; }
public string LastName { get; set; }
public string PasswordHash { get; set; }
public int InstitutionId { get; set; }
public virtual Institution Institution { get; set; }
public int RoleId { get; set; } <-------
public Role Role { get; set; } <-------
Migracja sie udaje tabela się tworzy ale podczas dodawania początkowych wartości wyskakuje wyjątek:
SqlException: The MERGE statement conflicted with the FOREIGN KEY constraint "FK_Customers_Roles_RoledId". The conflict occurred in database "InstytucjeDb', table "dbo.Roles", column 'Id'.
Tutaj jeszcze klasa tworząca baze danych i początkowe wartości, może tu jest coś źle:
Tworząca klase:
public class InstitutionDbContext : DbContext
{
private string _connectionString =
"Server=(localdb)\\mssqllocaldb; Database= InstytucjeDb; Trusted_Connection=True;";
public DbSet<Institution> Institutions { get; set; }
public DbSet<Customer> Customers { get; set; }
public DbSet<Role> Roles { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Role>()
.Property(r => r.Name)
.IsRequired();
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(_connectionString);
}
}
Początkowe wartości:
private readonly InstitutionDbContext _dbContext;
public InstitutionSeeder(InstitutionDbContext dbContext)
{
_dbContext = dbContext;
}
public void Seed()
{
if (_dbContext.Database.CanConnect())
{
if (!_dbContext.Roles.Any())
{
var roles = GetRoles();
_dbContext.Roles.AddRange(roles);
_dbContext.SaveChanges();
}
if (!_dbContext.Institutions.Any())
{
var institutions = GetInstitution();
_dbContext.Institutions.AddRange(institutions);
_dbContext.SaveChanges(); <----- W TYM MIEJSCU WYRZUCA WYJATEK
}
}
}
private IEnumerable<Role> GetRoles()
{
var roles = new List<Role>()
{
new Role()
{
Name = "Customer"
},
new Role()
{
Name = "Admin"
}
};
return roles;
}