[英]Can't retrieve EF Foreign Key values in WebAPI, DTO, AutoMapper and .NET Core using VS Code
I have a problem trying to retrieve the foreign key values from .NET Core C# RESTAPI application.我在尝试从 .NET Core C# RESTAPI 应用程序检索外键值时遇到问题。 I am using Code First.我正在使用代码优先。 It's been bugging me and I cannot see what is the issue.它一直困扰着我,我看不出是什么问题。 I have a simple table that has a FK in it to a user table.我有一个简单的表,其中有一个 FK 到用户表。
public class TripRouteDaySum
{
public int Id { get; set; }
public int YearNum {get; set;}
public int MonthNum {get; set;}
public int DayNum {get; set;}
public int HourNum { get; set;}
[Column(TypeName="decimal(12,2)")]
public Nullable<decimal> DistanceSum { get; set; }
[Column(TypeName="decimal(12,2)")]
public Nullable<decimal> CarbonSum { get; set; }
public User User {get; set;}
public Mode Mode {get; set;}
}
Using Code First migration Produces:使用 Code First 迁移产生:
So to retrieve it I set up a DTO with AutoMapper (set just to CreateMap as normal)因此,为了检索它,我使用 AutoMapper 设置了一个 DTO(照常设置为 CreateMap)
public class TripRouteDaySumDto
{
public int UserId {get; set;}
public int ModeId {get; set;}
public int YearNum {get; set;}
public int MonthNum {get; set;}
public int DayNum {get; set;}
public int HourNum {get; set;}
public decimal DistanceSum { get; set;}
public decimal CarbonSum { get; set;}
}
I then run the query against this:然后我对此运行查询:
public IEnumerable<TripRouteDaySum> GetTripRouteDaySum(int userId, int yearNum, int monthNum, int dayNum, bool trackChanges) =>
FindByCondition(c=> c.User.Id.Equals(userId)
&& c.YearNum.Equals(yearNum)
&& c.MonthNum.Equals(monthNum)
&& c.DayNum.Equals(dayNum), trackChanges)
.ToList();
And during Info running on the server I can see that the query is recovering all relevant data.在服务器上运行 Info 期间,我可以看到查询正在恢复所有相关数据。
But when I respond in JSON I get the userId and modeId = 0 when clearly they are none zero in reality.但是,当我在 JSON 中回复时,我得到了 userId 和 modeId = 0,而实际上它们显然不为零。
Do I need to embellish mapping?我需要修饰映射吗? Can my query be improved?我的查询可以改进吗? Is my DTO definition wrong?我的 DTO 定义有误吗?
If I was you, I would just add the below to TripRouteDaySum
.如果我是你,我只会将以下内容添加到TripRouteDaySum
。
public int UserId { get; set; }
public int ModeId { get; set; }
AutoMapper will be able to map them then because they have the same name in your entity and your DTO. AutoMapper 将能够 map 它们,因为它们在您的实体和 DTO 中具有相同的名称。
It would also make your filtering a bit easier, as you can replace它还可以使您的过滤更容易一些,因为您可以替换
FindByCondition(c=> c.User.Id.Equals(userId)
with和
FindByCondition(c=> c.UserId.Equals(userId)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.