i'm starting with EF6.1 CodeFirst with and existing batabase. I have the following Tables:
Company
ID integer
Code varchar
Currency_ID integer
Currency
ID integer
Company_ID integer
Code varchar
The concept behind is, that every table contains a reference to the Company_ID. I've created the following classes:
class Company
{
public int ID { get; set; }
public string Code { get; set; }
[ForeignKey("Currency")
public int? Currency_ID { get; set; }
public virtual Currency Currency { get; set; }
}
class Currency
{
public int ID { get; set; }
public string Code { get; set; }
[ForeignKey("Company")
public int? Company_ID { get; set; }
public virtual Company Company { get; set; }
}
When i use this model, i get the error
Company_Currency_Target: : Multiplicity is not valid in Role 'Company_Currency_Target' in relationship 'Company_Currency'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.
is there a solution other than adding a ICollection<Currency> CurrencyList to the Company Class?
--- Update ----
Here some Sample Data:
Company ID: 1 Code: XXX Curreny_ID: 100
Company ID: 2 Code: YYY Curreny_ID: 102
Currency ID: 100 Code: EUR Company_ID: 1
Currency ID: 101 Code: DOL Company_ID: 1
Currency ID: 102 Code: EUR Company_ID: 2
--- Update 2 ----
I found a possible solution using the fluent api
modelBuilder.Entity<Company>().HasOptional(q => q.Currency).WithMany().HasForeignKey(q => q.Currency_Id);
modelBuilder.Entity<Currency>().HasRequired(q => q.Company).WithMany().HasForeignKey(q => q.Company_Id);
is there a way to do the same using attirbutes?
ForeignKeyattribute on the wrong property. It should be the association not the foreign key.msdn.microsoft.com/en-us/data/jj591583#Relationships - Aron