Witam.
Chciałbym do jednej tabeli w bazie danych wrzucić 2 różne entity. Czy jest taka możliwość? Jeśli tak to w jaki sposób to można zrealizować?
Moja próba:
using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.EntityFrameworkCore;
namespace Test
{
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string Surname { get; set; }
public DateTime DateBirth { get; set; }
}
public class Employee
{
public int Id { get; set; }
public string FirstName { get; set; }
public string Surname { get; set; }
}
public class DataContext : DbContext
{
public virtual DbSet<Person> Person { get; set; }
public virtual DbSet<Employee> Employee { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseMySql(@"Server=localhost;database=ef;uid=root;pwd=qwerty;port=3307");
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>(entity =>
{
entity.ToTable("Person");
entity.HasKey(x => x.Id);
entity.Property(x => x.Surname).HasColumnName("Surname");
entity.Property(x => x.FirstName).HasColumnName("FirstName");
entity.Property(x => x.DateBirth).HasColumnName("DateBirth");
});
modelBuilder.Entity<Employee>(entity =>
{
entity.ToTable("Person");
entity.HasKey(x => x.Id);
entity.Property(x => x.Surname).HasColumnName("Surname");
entity.Property(x => x.FirstName).HasColumnName("FirstName");
});
}
}
public class Program
{
public static void Main()
{
using (var context = new DataContext())
{
var person = new Person
{
FirstName = "Jan",
Surname = "Kowalski",
DateBirth = DateTime.Now
};
context.Add(person);
context.SaveChanges();
var employe = new Employee();
employe.FirstName = "Piotr";
employe.Surname = "Nowak";
context.Add(employe);
context.SaveChanges();
}
}
}
}
Unhandled Exception: System.InvalidOperationException: Cannot use table 'Person' for entity type 'Person' since it is being used for entity type 'Employee' and there is no relationship between the primary key {'Id'} and the primary key {'Id'}.