EntityFramework + ASP WebAPI + SelfReference模型

时间:2014-09-16 08:29:32

标签: c# entity-framework asp.net-web-api

我正在使用Entity Framework和ASP WebAPI编写Simple数据库项目。

我正在努力创建一个具有自我参考的模型。

像:

public class ProductCategory
{
    [Key]
    public int CategoryID { get; set; }

    public string CategoryName { get; set; }
    public ProductCategory ParentCategory { get; set; }
}

我已经创建了API,我想创建新的ProductCategory,或者如果可能的话,创建类别的完整参考路径:

  • 第1类
    • 类别1.1
      • 类别1.1.1

此外,当我要访问帮助页面时,它会显示错误Object graph for type contains cycles and cannot be serialized if reference tracking is disabled.

要修复我发现我需要将[DataContract(IsReference = true)]添加到ProductCategory类,但我仍然不知道如何使用POST来创建新对象(对象图)

有人可以帮我吗?

编辑: 现在,我尝试过简单的POST方法(使用CategoryName),如:

{
    "CategoryName":"test"
}

但这会返回500错误:

Project.Models.ProductCategory_ParentCategory: : Multiplicity conflicts with the referential constraint in Role 'ProductCategory_ParentCategory_Target' in relationship 'ProductCategory_ParentCategory'. Because all of the properties in the Dependent Role are non-nullable, multiplicity of the Principal Role must be '1'.

ProductCategory_ParentCategory_Source: : Multiplicity is not valid in Role 'ProductCategory_ParentCategory_Source' in relationship 'ProductCategory_ParentCategory'. Because the Dependent Role refers to the key properties, the upper bound of the multiplicity of the Dependent Role must be '1'

同样的问题是我在尝试定义其他属性。但它应该使用明确的“CategoryName”属性集。

1 个答案:

答案 0 :(得分:3)

你需要设置一个可以为空的外键,因为EF按照惯例推断的关系意味着每个记录都有一个父级,这显然是不可能的,因为某些项必须是根。请尝试以下方法:

public class ProductCategory
{
    [Key]
    public int CategoryID { get; set; }

    [ForeignKey("ParentCategory")]
    public int? ParentCategoryId {get;set;}

    public string CategoryName { get; set; }
    public ProductCategory ParentCategory { get; set; }
}
相关问题