Как решить проблему отсутствия в столбце внешнего ключа EF-Core Code-First таблицы - PullRequest
0 голосов
/ 20 марта 2019

Я изучаю EF Core, и ниже мои три POCO:

public class County
{
    [Key]
    public int cid { get; set; }
    public string cname { get; set; }
}

public class City
{
    [Key]
    public int cid { get; set; }
    public string cname { get; set; }
}

public class People
{
    [Key]
    public int pid { get; set; }
    public string pname { get; set; }

    public int cid { get; set; }
    public City WhichCity { get; set; }

}

Я ожидаю два внешних ключа, но получил только один из таблицы City. Как сделать это (используя аннотацию или свободный API или что-то еще), кроме явного определения переменной County для класса People.

1 Ответ

1 голос
/ 20 марта 2019

Просто хочу уточнить: вам не нужно иметь свойства навигации, т. Е. public City City { get; set; }, чтобы установить отношения.Единственное, что вам нужно, это внешний ключ и правильные конфигурации.

Я думаю, что следующая конфигурация будет работать для вас (хотя не проверено):

Сущности

Здесь я такжепреднамеренно изменили ваши существующие классы, чтобы они следовали C # Naming Conventions , если вам это нужно.Помните, что если вы делаете Code First, это означает, что вы можете проводить занятия так, как вам хочется.Вы думаете о настойчивости позже.На самом деле я покажу вам, как вы можете переименовывать свойства классов, когда вы сохраняете их в своей базе данных через конфигурации.

public class County
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class City
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class People
{
    public int Id { get; set; }
    public string Name { get; set; }

    public int CityId { get; set; }
    // Optional
    //public City City { get; set; }

    public int CountyId { get; set; }
    // Optional
    //public County County { get; set; }
}

конфигурации

Вместо использования аннотации данных вы можете использовать Fluent API сконфигурации для настройки того, как вы хотите отобразить ваши классы обратно в базу данных.

public class CountyConfiguration : IEntityTypeConfiguration<County>
{
    public void Configure(EntityTypeBuilder<County> builder)
    {
        builder.HasKey(x => x.Id);        // Same as using [Key]

        builder.Property(x => x.Id)
            .HasColumnName("cid");        // If you want to rename to "cid"

        builder.Property(x => x.Name)
            .IsRequired()                 // If you want to mark that field required
            .HasColumnName("cname");      // If you want to rename to "cname"

        builder.ToTable("so_county");     // If you want to rename the table
    }
}

public class CityConfiguration : IEntityTypeConfiguration<City>
{
    public void Configure(EntityTypeBuilder<City> builder)
    {
        builder.HasKey(x => x.Id);        // Same as using [Key]

        builder.Property(x => x.Id)
            .HasColumnName("cid");        // If you want to rename to "cid"

        builder.Property(x => x.Name)
            .IsRequired()                 // If you want to mark that field required
            .HasColumnName("cname");      // If you want to rename to "cname"

        builder.ToTable("so_city");       // If you want to rename the table
    }
}

public class PeopleConfiguration : IEntityTypeConfiguration<People>
{
    public void Configure(EntityTypeBuilder<People> builder)
    {
        builder.HasKey(x => x.Id);        // Same as using [Key]

        builder.Property(x => x.Id)
            .HasColumnName("pid");        // If you want to rename to "pid"

        builder.Property(x => x.Name)
            .IsRequired()                 // If you want to mark that field required
            .HasColumnName("pname");      // If you want to rename to "pname"

        // Relationship
        builder.HasOne<County>()          // People has one County
            .WithMany()                   // County has many people
            .HasForeignKey<County>(x => x.CountyId);  // Foreign key is CountyId

        builder.HasOne<City>()            // People has one City
            .WithMany()                   // City has many people
            .HasForeignKey<City>(x => x.CityId);      // Foreign key is CityId

        builder.ToTable("so_people");     // If you want to rename the table
    }
}

И, наконец, вам необходимо применить эти конфигурации OnModelCreating:

public class YourDbContext : DbContext
{
    public DbSet<County> Counties { get; set; }
    public DbSet<City> Cities { get; set; }
    public DbSet<People> People { get; set; }

    public YourDbContext(DbContextOptions<YourDbContext> options) : base(options) {}

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        builder.ApplyConfiguration(new CountyConfiguration());
        builder.ApplyConfiguration(new CityConfiguration());
        builder.ApplyConfiguration(new PeopleConfiguration());
    }
}

ОТКАЗ ОТ ОТВЕТСТВЕННОСТИ : написал это от руки.Не проверено.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...