【发布时间】:2014-09-10 23:49:21
【问题描述】:
public partial class User
{
public System.Guid UserId { get; set; }
public Nullable<System.Guid> RoleId { get; set; }
public Nullable<long> MembershipNo { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public string Emaiil { get; set; }
public Nullable<decimal> MobileNo { get; set; }
public string Description { get; set; }
public Nullable<System.Guid> ModifiedBy { get; set; }
public Nullable<System.DateTime> ModifiedDate { get; set; }
public virtual Role Role { get; set; }
}
这是我在名为 Users 的 DB 中的表,它与 DB 的 Roles 表相关联(您可以在上面看到最后一个虚拟行)
现在我的问题很简单。我正在使用 angulars $http.get() 方法在 MVC 4 中调用我的 Web Api。当我调用它时,它会连接并获取所需的记录,但它不会将正确的结果返回给 .js 文件或控制器。 在 .js 方面我遇到了错误。每次都会执行 .error(jsonResult,config,header,status) 。
当我跳转到 JsonResult 时,它会显示以下错误。
Object
ExceptionMessage: "The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'."
ExceptionType: "System.InvalidOperationException"
InnerException: Object
ExceptionMessage: "Self referencing loop detected for property 'Role' with type
'System.Data.Entity.DynamicProxies.Role_82CA96EA045B1EB47E58B8FFD4472D86502EEA79837B4AE3AD705442F6236E58'.
Path 'Role.Users[0]'."
ExceptionType: "Newtonsoft.Json.JsonSerializationException"
Message: "An error has occurred."
我不知道这里出了什么问题。是json解析错误还是什么?如果是这样,我已经听过并阅读过 .net 中的 webapi 处理或抛出 json 本身的文章。
我的电话是通过
$http.get(apiUrl).success(function (jsonResult, header, config, status) {
debugger;
var number = parseInt(jsonResult.membershipNo) + 1;
$scope.membershipNo = "M" + number;
})
.error(function (jsonResult, header, config, status) {
debugger;
toastr.error('Something went wrong ! Contact Administrator!!!');
});
编辑:
还有一点要提一下,.CS 端当我获取单个单元格值(从 DB/表)时,它会返回到 .success() 调用,但是当我获取特定行或所有行时,它会返回到 .cs 端。错误()调用。我正在使用实体框架 6.1.1。及以上类由 EF-6.1.1 生成。
public partial class Role
{
public Role()
{
this.Permissions = new List<Permission>();
this.Users = new List<User>();
}
public System.Guid RoleId { get; set; }
public string RoleName { get; set; }
public string Description { get; set; }
public Nullable<System.Guid> ModifiedBy { get; set; }
public Nullable<System.DateTime> ModifiedDate { get; set; }
public virtual ICollection<Permission> Permissions { get; set; }
public virtual ICollection<User> Users { get; set; }
}
【问题讨论】:
-
当 asp.net web api 尝试将您的对象序列化为 JSON 时,它看起来像一个循环引用问题,如错误
Self referencing loop detected for property 'Role'中所述 -
嗯...应该是什么解决方案?
-
通常,当我们将对象序列化为 JSON 时,我们应该序列化视图模型对象 (DTO) 而不是您的域模型。
-
尝试将您的域模型对象转换为
flattened视图模型对象 (DTO):stackoverflow.com/questions/4061440/… -
你的角色类是什么。如果您在 Role 类中有 User 属性,请将其从序列化中排除或使用视图模型而不是域模型作为 Khanh TO sad。
标签: angularjs asp.net-mvc-4 asp.net-web-api