EF Code First Migration modelBuilder

时间:2015-03-28 12:19:45

标签: c# sql-server entity-framework

我的C#代码中有两个实体:

  public class Currency
{        
    public int CurrencyID { get; set; }

    public string CurrencyName { get; set; }

    public virtual ICollection<CurrencyRate> CurrentCurrencyRates { get; set; }
    public virtual ICollection<CurrencyRate> TargetCurrencyRates { get; set; }
}

 public class CurrencyRate
    {
        public int RateID { get; set; }
        public DateTime RateDate { get; set; }
        public Decimal RateValue { get; set; }
        public int CurrentCurrencyID { get; set; }
        public int TargetCurrencyID { get; set; }


        public virtual Currency CurrentCurrency { get; set; }
        public virtual Currency TargetCurrency { get; set; }
    }

我有Context Class:

public EconomicAppContext()
            : base("EconomicApp")
        { }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<CurrencyRate>().Property(v => v.RateValue).HasColumnType("Money");
            modelBuilder.Entity<CurrencyRate>().HasKey(cr => cr.RateID);
            modelBuilder.Entity<Currency>().HasKey(c => c.CurrencyID);

            modelBuilder.Entity<Currency>().
                HasMany<CurrencyRate>(c => c.CurrentCurrencyRates).
                WithRequired(c => c.CurrentCurrency).
                HasForeignKey(c => c.RateID);
            modelBuilder.Entity<Currency>().
               HasMany<CurrencyRate>(c => c.TargetCurrencyRates).
               WithRequired(c => c.TargetCurrency).
               HasForeignKey(c => c.RateID);

             base.OnModelCreating(modelBuilder);
        }

        public DbSet<CurrencyRate> CurrencyRates { get; set; }
        public DbSet<Currency> Currencies { get; set; }

我尝试迁移到现有数据库。我想得到这样的架构:

enter image description here

我做错了什么?可以有人帮我将表迁移到DB吗?

1 个答案:

答案 0 :(得分:1)

尝试以下内容:

modelBuilder.Entity<CurrencyRate>().
                HasRequired<Currency>(c => c.CurrentCurrency).
                WithMany(c => c.CurrentCurrencyRates).
                HasForeignKey(c => c.CurrentCurrencyID);
modelBuilder.Entity<CurrencyRate>().
               HasRequired<Currency>(c => c.TargetCurrency).
               WithMany(c => c.TargetCurrencyRates).
               HasForeignKey(c => c.TargetCurrencyID);