2016-04-05 17 views
1

Entity Framework ile bir yabancı anahtar üzerinde mücadele (birçok ilişkiden 1'e).'Class1' türünde 'MyField' özelliği üzerinde ForeignKeyAttribute geçerli değil

sınıfı1: Ben fluentAPI ile çalıştı

public partial class Class1 
    { 

     public int Id { get; set; } 
     [ForeignKey("Class2_Id")] 
     public Class2 Class2{ get; set; } 
...} 

Class2: 
public partial class Class2 
    { 

     public int Id { get; set; } 
     public virtual ICollection<Class1> Stuff{ get; set; } 
...} 

1): 1 deneyin:

2 deneyin

modelBuilder.Entity<Class2>().HasMany<Class1>(p => p.Stuff).WithOptional().Map(m => m.MapKey("Class2_Id")).WillCascadeOnDelete(); 
:

modelBuilder.Entity<Class1>().HasRequired(i => i.Class2).WithMany().Map(m => m.MapKey("Class2_Id")); 

2) fluentAPI olmadan: ben ilan ilgili Class2 bu şekilde:

0 neyin yanlış olduğunu

The ForeignKeyAttribute on property 'Class2' on type 'Class1' is not valid. The foreign key name 'Class2_Id' was not found on the dependent type 'Class1'. The Name value should be a comma separated list of foreign key property names.

konusunda fikrin:

[ForeignKey("Class2")] 
public int Id { get; set; } 

Her zaman bu hatayı alıyorum:

[Column("Class2")] 
public int Id { get; set; } 

bile (muhtemelen hiçbir mantıklı)? Önceden

. senin akıcı API yapılandırmaları Eğer tek yönlü bir ilişki tanımlayarak, bu yüzden doğru yol olacaktır ile

cevap

1

: Eğer bir özelliği olarak yabancı anahtara sahip istemediğinizde

modelBuilder.Entity<Class2>().HasMany(p => p.Stuff) 
          .WithOptional(c=>c.Class2) 
          .Map(m => m.MapKey("Class2_Id")) 
          .WillCascadeOnDelete(); 

MapKey yöntemi kullanılırsa sizin model sınıfı.

public partial class Class1 
{ 

    public int Id { get; set; } 

    public int? Class2_Id{ get; set; } 

    [ForeignKey("Class2_Id")] 
    public Class2 Class2{ get; set; } 
} 

bu son durumda Akıcı Api'si ile ilişkiniz yapılandırma olacaktır:

modelBuilder.Entity<Class2>().HasMany(p => p.Stuff) 
          .WithOptional(c=>c.Class2) 
          .HasForeignKey(c=>c.Class2_Id)) 
          .WillCascadeOnDelete(); 
+0

Büyük açıklama octavioccl

Kullanımı ForeignKey özellik size varlığın bir özelliği olarak FK sütununu temsil zaman. Çok teşekkür ederim! –

+0

hoşgeldiniz;) – octavioccl

İlgili konular