我正在使用实体框架和ASP WebAPI编写简单的数据库项目。
我在努力创造一个有自我参照的模型。
比如:
public class ProductCategory
{
[Key]
public int CategoryID { get; set; }
public string CategoryName { get; set; }
public ProductCategory ParentCategory { get; set; }
}我已经创建了API,我希望创建新的ProductCategory,或者,如果可能的话,创建整个类别引用路径(例如:
此外,当我要帮助页面时,它会显示错误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“属性集一起工作。
发布于 2014-09-16 09:01:21
您需要设置一个可为空的外键,因为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; }
}https://stackoverflow.com/questions/25864018
复制相似问题