C# 在Azure移动服务.NET中使用DTO引发目标调用异常
我使用Azure Mobile Services.NET后端,我们都知道必须使用实体框架类来映射到数据库创建/迁移。 因此,我需要使用DTO来序列化我想要的属性、计算属性等。但汽车制造商给了我这么多的痛苦,虽然我做了一切应该做的 我已经检查了其他几个博客和网站,例如,一些使用Automapper,另一些不使用Automapper。我觉得不使用Automapper和使用Select()动态创建DTO会更舒服,就像我以前在实现Web API时那样 我将TableController类还原为Post,使用EntityDomainManager,并将GetAllPosts方法保留为以下内容C# 在Azure移动服务.NET中使用DTO引发目标调用异常,c#,.net,entity-framework,azure-mobile-services,dto,C#,.net,Entity Framework,Azure Mobile Services,Dto,我使用Azure Mobile Services.NET后端,我们都知道必须使用实体框架类来映射到数据库创建/迁移。 因此,我需要使用DTO来序列化我想要的属性、计算属性等。但汽车制造商给了我这么多的痛苦,虽然我做了一切应该做的 我已经检查了其他几个博客和网站,例如,一些使用Automapper,另一些不使用Automapper。我觉得不使用Automapper和使用Select()动态创建DTO会更舒服,就像我以前在实现Web API时那样 我将TableController类还原为Post,
public class PostController : TableController<Post>
{
private MobileServiceContext _context;
protected override void Initialize(HttpControllerContext controllerContext)
{
base.Initialize(controllerContext);
_context = new MobileServiceContext();
DomainManager = new EntityDomainManager<Post>(_context, Request, Services);
}
//[ExpandProperty("User")]
// GET tables/Post
public IQueryable<PostDto> GetAllPost()
{
return Query().Include("User").Select(x => new PostDto());
}
}
异常快照:
我真的不需要这个项目的DTO,但是如果我现在不解决我不理解的问题,它会回来并在这个服务的长期运行中找到我。我不确定,但我认为问题可能在于这行代码
return Query().Include("User").Select(x => new PostDto());
如果您没有使用AutoMapper,那么您将需要手动解析Select语句中的属性,如下所示
return Query().Include("User")
.Select(x => new PostDto()
{
DatePosted = x.DatePosted,
StatusText = x.StatusText,
TypeOfPost = x.TypeOfPost,
User = new UserDto
{
//Your propertoes here
//eg Id = x.User.Id etc
}
);
似乎Select()LINQ表达式在元素完全加载或引用仍然未设置之前发生冲突。
我将该方法转换为IEnumerable返回类型,并在转换为DTO之前加载数据
public IEnumerable<PostDto> GetAllPost()
{
return Query().Include("User").ToList().Select(x => new PostDto
{
DatePosted = x.DatePosted,
StatusText = x.StatusText,
TypeOfPost = (int)x.TypeOfPost,
User = new UserDto
{
Id = x.User.Id
}
});
}
现在应该使用AutoMapper进行测试,以涵盖它也可以使用它
唯一未知的一点是为什么我需要将ReferenceLoopHandling
属性设置为Ignore
,以便服务正确显示JSON样本数据
return Query().Include("User").Select(x => new PostDto());
return Query().Include("User")
.Select(x => new PostDto()
{
DatePosted = x.DatePosted,
StatusText = x.StatusText,
TypeOfPost = x.TypeOfPost,
User = new UserDto
{
//Your propertoes here
//eg Id = x.User.Id etc
}
);
public IEnumerable<PostDto> GetAllPost()
{
return Query().Include("User").ToList().Select(x => new PostDto
{
DatePosted = x.DatePosted,
StatusText = x.StatusText,
TypeOfPost = (int)x.TypeOfPost,
User = new UserDto
{
Id = x.User.Id
}
});
}
[
{
"datePosted": "2015-04-27T04:05:38.843Z",
"statusText": "Post Text",
"typeOfPost": 1,
"user": {
"id": "a59d0f12-8bb1-448e-9c08-56f862b77ee4"
},
"photoUrls": []
}
]
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;