在实体框架4.1外键 [英] Foreign keys in entity framework 4.1

查看:237
本文介绍了在实体框架4.1外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的实体框架4.1,并使用数据注释外键。我想知道我们如何能够定义一个产品和类别之间一对多的关系。我要地图类别。的categoryId与product.cid

I am working on Entity Framework 4.1 and using data annotations for foreign keys. I want to know how can we define one to many relationship between product and categories. I want to map category. categoryId with product.cid

public class Category
{
    public string CategoryId { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Product> Products { get; set; }
}

public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }
    public string CId { get; set; }

    public virtual Category Category { get; set; }
} 

请提示

推荐答案

这两种方法应该工作:

public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }
    [ForeignKey("Category")]
    public string CId { get; set; }

    public virtual Category Category { get; set; }
}

或者

public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }
    public string CId { get; set; }

    [ForeignKey("CId")]
    public virtual Category Category { get; set; }
} 

ForeignKeyAttribute 用来配对导航属性和外键的属性。它包含了相关的导航属性的名称或相关的外键属性的名称。

ForeignKeyAttribute is used to pair navigation property and foreign key property. It contains either the name of related navigation property or the name of related foreign key property.

这篇关于在实体框架4.1外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆