C#实体图1:1或1:0

时间:2018-01-18 14:05:18

标签: c# entity-framework entity

我有两张桌子:

public class Atendimento {
   public int ID { get; set; } // PK
   ...
}

public class CaixaTransacao {
   public int ID { get; set; } // PK
   public int AtendimentoID { get; set; } // FK to Atendimento
   ...
}

我在Atendimento上创建了一个引用CaixaTransacao的属性,所以我做了:

public class Atendimento {
   public ID { get; set; } // PK
   ...

   public virtual CaixaTransacao Transacao { get; set; } 
}

我试图映射它:

HasOptional(x => x.Transacao)
   .WithRequired(x => x.Atendimento)

但它将Atendimento.ID引用到CaixaTransacao.ID,这是错误的。

如何将Atendimento.ID映射到CaixaTransacao.AtendimentoID?

唯一有效的方法:

public class Atendimento {
   public int ID { get; set; }
   ...

   public ICollection<CaixaTransacao> ListTransacao { get; set; }
}

并映射:

HasMany(x => x.ListTransacao)
   .WithOptional()
   .HasForeignKey(x => x.AtendimentoID);

这是实现我想要的唯一途径和正确方法吗?因为列表似乎不是一个干净的解决方案......

1 个答案:

答案 0 :(得分:0)

试试这个:

    public class Atendimento
    {
        public int Id { get; set; }
        public string Field1 { get; set; }

        public virtual CaixaTransacao CaixaTransacao { get; set; }
    }

    public class CaixaTransacao
    {
        public int Id { get; set; }
        public string Field2 { get; set; }
        public string Field3 { get; set; }

        // public int AtendimentoID { get; set; } // DELETE THIS ROW. See OnModelCreating

        public virtual Atendimento Atendimento { get; set; }
    }

...

在您的DbContext类

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        // Primary keys
        modelBuilder.Entity<Atendimento>().HasKey(a => a.Id);
        modelBuilder.Entity<CaixaTransacao>().HasKey(c => c.Id);

        // Foreign Key
        modelBuilder.Entity<Atendimento>()
                    .HasOptional(a => a.CaixaTransacao)
                    .WithRequired(c => c.Atendimento)
                    .Map(c => c.MapKey("AtendimentoId")); // here we show the column for FK
    }

一个副作用就是这个

    var q1 = db.Atendimentoes
               .Select(a => new
                            {
                                AId = a.Id,
                                AField = a.Field1,
                                CId = a.CaixaTransacao.Id,
                                CField1 = a.CaixaTransacao.Field2,
                                CField2 = a.CaixaTransacao.Field3
                            }).ToList();
生成的SQL中的

将是2(!!!)LEFT JOINS

    SELECT
        [Extent1].[Id] AS [Id],
        [Extent1].[Field1] AS [Field1],
        [Extent2].[Id] AS [id1],
        [Extent3].[Field2] AS [Field2],
        [Extent3].[Field3] AS [Field3]
        FROM   [sample].[Atendimentoes] AS [Extent1]
        LEFT OUTER JOIN [sample].[CaixaTransacaos] AS [Extent2] ON [Extent1].[Id] = [Extent2].[AtendimentoId]
        LEFT OUTER JOIN [sample].[CaixaTransacaos] AS [Extent3] ON [Extent1].[Id] = [Extent3].[AtendimentoId]