Entity Framework Fluent API Mapping Проблема

Как я могу настроить отношения между тремя таблицами, чтобы получить все связанные данные?

У меня есть следующие модели (и те же таблицы в базе данных):

public class Client 
{
  public Guid ClientId { get; set; }
  public string FirstName { get; set; }

  public virtual ClientCard ClientCard { get; set; }
}

public class Card
{
  public Guid CardId { get; set; }
  public string Number { get; set; }

  public virtual ClientCard ClientCard { get; set; }
}

public class ClientCard
{
  public Guid ClientCardId { get; set; }
  public Guid CardId { get; set; }
  public Guid ClientId { get; set; }

  public virtual Client Client { get; set; }
  public virtual Card Card { get; set; }
}

И следующий метод OnModelCreating:

protected override void OnModelCreating(DbModelBuilder builder)
    {
        builder.Conventions.Remove<PluralizingTableNameConvention>();

        ...

        builder.Entity<ClientCard>()
            .HasKey(x => x.ClientCardId);

        builder.Entity<ClientCard>()
            .HasRequired(x => x.Client)
            .WithRequiredPrincipal(x => x.ClientCard);

        builder.Entity<ClientCard>()
            .HasRequired(x => x.Card)
            .WithRequiredPrincipal(x => x.ClientCard);

        base.OnModelCreating(builder);
    }

Но результаты возвращаются без соответствующих данных. Зачем?

3 ответа

Для вашего кода, пожалуйста, попробуйте что-то вроде:

public class Client 
{
  public Guid ClientId { get; set; }
  public string FirstName { get; set; }

  public virtual ICollection<ClientCard> ClientCard { get; set; }
}

public class Card
{
  public Guid CardId { get; set; }
  public string Number { get; set; }

  public virtual ICollection<ClientCard> ClientCard { get; set; }
}

public class ClientCard
{
  public Guid ClientCardId { get; set; }
  public Guid CardId { get; set; }
  public Guid ClientId { get; set; }

  public virtual Client Client { get; set; }
  public virtual Card Card { get; set; }
}

И отображение:

    builder.Entity<Client>()
           .HasKey(t => t.ClinetID);
    ....
    builder.Entity<Client>()
           .HasMany(a => a.ClientCard)
           .WithRequired(p => p.Client)
           .HasForeignKey(p => p.ClientID);

Для карты

    ....
    builder.Entity<Card>()
           .HasMany(a => a.ClientCard)
           .WithRequired(p => p.Card)
           .HasForeignKey(p => p.CardID);

Но я думаю, что лучший способ - создать отдельный файл карты для каждой сущности.

Я наконец нашел решение для своего случая.

Сначала я удалил CardId из класса Client. Во-вторых, я изменил свой метод OnModelCreating:

protected override void OnModelCreating(DbModelBuilder builder)
    {
        builder.Conventions.Remove<PluralizingTableNameConvention>();

        ...

        builder.Entity<Client>()
            .HasOptional(x => x.Card)
            .WithOptionalDependent(x => x.Client)
            .Map(x => x.MapKey("CardId"))
            .WillCascadeOnDelete(false);

        builder.Entity<Card>()
            .HasOptional(x => x.Client)
            .WithOptionalPrincipal(x => x.Card)
            .WillCascadeOnDelete(false);

        base.OnModelCreating(builder);
    }

Сейчас я использую следующие модели:

public class Client 
{
   public Guid ClientId { get; set; }
   public string FirstName { get; set; }

   public Guid? CardId { get; set; }
   public virtual Card Card { get; set; }
}

public class Card
{
   public Guid CardId { get; set; }
   public string Number { get; set; }

   //public virtual Client Client { get; set; }
}

и следующий метод OnModelCreating:

protected override void OnModelCreating(DbModelBuilder builder)
{
        builder.Conventions.Remove<PluralizingTableNameConvention>();

        ... 

        builder.Entity<Client>()
            .HasOptional(x => x.Card)
            //.WithOptionalPrincipal(x=> x.Client) 
            //or
            //.WithOptionalDependent(x=> x.Client)
            ;

        base.OnModelCreating(builder);
}

Все клиенты возвращаются со связанными данными (если есть). Но если я хочу получить сопоставленные данные с объектом Card и раскомментировать public virtual Client Client { get; set; } и WithOptionalPrincipal/WithOptionalDependent Я всегда получаю следующие SqlException: "недопустимое имя столбца" Client_ClientId "" (если используется WithOptionalPrincipal) ИЛИ "недопустимое имя столбца" Card_CardId "" (если используется WithOptionalDependent)

Другие вопросы по тегам