首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >EntityFramework + ASP WebAPI + SelfReference模型

EntityFramework + ASP WebAPI + SelfReference模型
EN

Stack Overflow用户
提问于 2014-09-16 08:29:31
回答 1查看 201关注 0票数 1

我正在使用实体框架和ASP WebAPI编写简单的数据库项目。

我在努力创造一个有自我参照的模型。

比如:

代码语言:javascript
复制
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),例如:

代码语言:javascript
复制
{
    "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“属性集一起工作。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-09-16 09:01:21

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

代码语言:javascript
复制
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; }
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25864018

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档