Tuesday, January 24, 2012

C# Entity Framework Code First

The task is - create two SQL tables.
Where second table has foreign key from the first table as part of primary key.
Like this - in MS SQL :
Table Currency
Code char(3) Primary Key, Not null
Description varchar(50) Not null

Table ExchangeRate
Currency_Code char(3) Primary Key, Not Null, Foreign Key reference Currency(Code)
EffectiveDate Date Primary Key, Not Null
Rate Decimal (17,2)

Problem is how to make it in C# - Code First.
I did it this way.

public class Currency
{
public string Code { get; set; }
public string Description { get; set; }
public virtual ICollection ExchangeRates { get; set; }
}

public class ExchangeRate
{
public decimal Rate { get; set; }
public DateTime EffectiveDate { get; set; }
public Currency Currency { get; set; }
internal string Currency_Code { get { return this.Currency.Code; } set { this.Currency.Code=value; } }
public ExchangeRate() { Currency = new Currency(); } }

public class CurrencyConfiguration : EntityTypeConfiguration
{
public CurrencyConfiguration()
{
Property(d => d.Code).IsRequired().HasMaxLength(3).IsFixedLength();
Property(d => d.Description).IsRequired().HasMaxLength(50);
HasKey(d => d.Code);
}
}

public class ExchangeRateConfiguration : EntityTypeConfiguration
{
public ExchangeRateConfiguration()
{
Property(d => d.Currency_Code).IsRequired().HasMaxLength(3).IsFixedLength();
Property(d => d.EffectiveDate).IsRequired();
Property(d => d.Rate).IsRequired();
HasKey(d => new { d.Currency_Code, d.EffectiveDate } ); // Combined primary key
HasRequired(d => d.Currency).WithMany(e => e.ExchangeRates).HasForeignKey(d => d.Currency_Code);
}
}

No comments: