Asım Gündüz
Asım Gündüz

Reputation: 1297

Entity Framework codefirst 1 to many relations

using the codefirst approach, I would like to have a CODE_YESNO table where it will have two columns C_CODE(1) and C_DESC(5) both type of string.

then I would like to reference it to my other tables.

for example lets say I have I have USERS and PRODUCTS table

and for USERS table I will have userIsActive (foreign key C_CODE) and for PRODUCTS table I will have productIsOnDiscount (foreign key C_CODE)

I don't want to add or do any modifications on the CODE_YESNO table

so how do I do that with the code first approach?

Upvotes: 1

Views: 33

Answers (1)

Steve Greene
Steve Greene

Reputation: 12304

Personally, I would use a boolean if it is just Yes/No. But more generally you can implement lookup tables easily.

public class YesNo
{
    [Key]
    public string C_CODE { get; set; }
    public string C_DESC { get; set; }
}

Then your classes reference through navigation properties:

public class User
{
    public int UserId { get; set; }
    public string UserName { get; set; }

    public string UserIsActiveCode { get; set; }
    [ForeignKey("UserIsActiveCode")]
    public YesNo UserIsActive { get; set; }
}

public class Product
{
    public int ProductId { get; set; }
    public string ProductName { get; set; }

    public string ProductIsOnDiscountCode { get; set; }
    [ForeignKey("ProductIsOnDiscountCode")]
    public YesNo ProductIsOnDiscount { get; set; }
}

Upvotes: 2

Related Questions