我目前正在使用一个mvc4 web api odata服务,我想返回用户列表中的用户列表.当我想得到用户我得到以下错误:
错误:
<m:innererror> <m:message> The 'ObjectContent`1' type Failed to serialize the response body for content type 'application/json; charset=utf-8'. </m:message> <m:type>System.InvalidOperationException</m:type> <m:stacktrace/> <m:internalexception> <m:message> No NavigationLink factory was found for the navigation property 'Languages' from entity type 'MvcWebRole1.Models.User' on entity set 'Users'. Try calling HasNavigationPropertyLink on the EntitySetConfiguration. Parameter name: navigationProperty </m:message> <m:type>System.ArgumentException</m:type> <m:stacktrace> at System.Web.Http.OData.Builder.EntitySetLinkBuilderAnnotation.BuildNavigationLink(EntityInstanceContext instanceContext,IEdmNavigationProperty navigationProperty,ODataMetadataLevel MetadataLevel) at System.Web.Http.OData.Formatter.Serialization.ODataEntityTypeSerializer.WriteNavigationLinks(EntityInstanceContext context,ODataWriter writer,ODataSerializerContext writeContext) at System.Web.Http.OData.Formatter.Serialization.ODataEntityTypeSerializer.WriteEntry(Object graph,IEnumerable`1 propertyBag,ODataSerializerContext writeContext) at System.Web.Http.OData.Formatter.Serialization.ODataEntityTypeSerializer.WriteObjectInline(Object graph,ODataSerializerContext writeContext) at System.Web.Http.OData.Formatter.Serialization.ODataFeedSerializer.WriteFeed(Object graph,ODataSerializerContext writeContext) at System.Web.Http.OData.Formatter.Serialization.ODataFeedSerializer.WriteObjectInline(Object graph,ODataSerializerContext writeContext) at System.Web.Http.OData.Formatter.Serialization.ODataFeedSerializer.WriteObject(Object graph,ODataMessageWriter messageWriter,ODataSerializerContext writeContext) at System.Web.Http.OData.Formatter.ODataMediaTypeFormatter.<>c__DisplayClassa.<WriteToStreamAsync>b__9() at System.Threading.Tasks.TaskHelpers.RunSynchronously(Action action,CancellationToken token) </m:stacktrace> </m:internalexception> </m:innererror>
我的用户看起来像这样:
public class User { [Key] public int UserId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string UserName { get; set; } public string Password { get; set; } public virtual ICollection<Language> Languages { get; set; } public User() { Languages = new List<Language>(); } }
而我的UsersController for OData看起来像这样:
public class UsersController : EntitySetController<User,int> { WorldChatContext db = new WorldChatContext(); public override IQueryable<User> Get() { return db.Users.AsQueryable(); } protected override User GetEntityByKey(int key) { return db.Users.FirstOrDefault(p => p.UserId == key); } public override HttpResponseMessage Post(User entity) { db.Users.Add(entity); db.SaveChanges(); return base.Post(entity); } }
我正在呼叫我在路由中设置的以下url:http://127.0.0.1:81/odata/如果我在我的用户模型中注释了导航属性,则可以使用它.
我究竟做错了什么?我已经尝试将[Serializable,KnownType(typeof(Language))]放在我的用户类之上,但由于某种原因我不能使用KnownType.我如何使我的OData与此导航属性一起使用?