2011-10-07 25 views
9

Bire ben şu iki modelVarlık Framework Kod İlk olan İlişki

public class Account 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public int CurrentPeriodId { get; set; } 

    [ForeignKey("CurrentPeriodId")] 
    public virtual Period CurrentPeriod { get; set; } 

    public virtual ICollection<Period> Periods { get; set; } 
} 

public class Period 
{ 
    public int Id { get; set; } 
    public int AccountId { get; set; } 
    public DateTime StartDate { get; set; } 
    public DateTime EndDate { get; set; } 

    public virtual Account Account { get; set; } 
} 

Ve aşağıdaki sorguyu çalıştırmak çalışıyorum:

from p in context.Periods 
where p.AccountId == accountId && 
     p.Id == p.Account.CurrentPeriodId 
select p.StartDate 

Ve Geçersiz" diyerek bir sql istisna olsun sütun adı Account_AccountId ".

ben Hesap taraftan bu yaklaşım biliyorum ve

from a in context.Accounts 
where a.Id == id 
select a.CurrentPeriod.StartDate 

böyle bir şey yapmak Ama ilişki diğer sorgu işe almak için nasıl ayarlanacağını bilmek istiyorum. Neyi kaçırıyorum?

cevap

8

Uygulamanızın yanlış olduğunu düşünüyorum. AFAIK, EF'de bu yaklaşımı kullanarak bire bir ilişki tanımlayamazsınız.
Oluşturduğunuz veritabanına bir göz atın, Periods tablonuzda tanımlanmış bir Account_Id sütun var. Burada tanımlamak zorunda budur:

public class Account 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public int CurrentPeriodId { get; set; } 
    public virtual Period CurrentPeriod { get; set; } 
    public virtual ICollection<Period> Periods { get; set; } 
} 

public class Period 
{ 
    public int Id { get; set; } 
    public DateTime StartDate { get; set; } 
    public DateTime EndDate { get; set; } 
} 

Sonra bağlam ve başlatıcı: Daha fazla bilgi için

public class TestContext : DbContext 
{ 
    public DbSet<Account> Accounts { get; set; } 
    public DbSet<Period> Periods { get; set; } 

static TestContext() 
{ 
    Database.SetInitializer(new DbInitializer()); 
} 

    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     modelBuilder.Entity<Account>().HasRequired(a => a.CurrentPeriod).WithMany().HasForeignKey(a => a.CurrentPeriodId); 
    } 
} 

class DbInitializer : DropCreateDatabaseAlways<TestContext> 
{ 
    protected override void Seed(TestContext context) 
    { 
     context.Database.ExecuteSqlCommand("ALTER TABLE Accounts ADD CONSTRAINT uc_Period UNIQUE(CurrentPeriodId)"); 
    } 
} 

yaklaşık Bire Bir ilişki, this address Sn Manavinin blog dizisi okundu.
Güncelleme: Eğer Period den Account bir başvuru yapmak istiyorsanız
Yorumlarınız dayanarak, hesabınızın birincil anahtar üzerinde ForeignKey niteliğini koyabilirsiniz.

İyi örnek this address bulunmaktadır olsa Döneminden Hesap benim referans kaybetmiş bu çözüm sayesinde

+0

(başlıkla parçası "Bir Sıfır biri veya bir İlişki Harita"). –

+0

@Nick Olsen: Cevabımı güncelledi. – Kamyar

İlgili konular