[英]How to retrieve a subset of columns in a foreign-key relationship in Entity Framework with Data Annotations
假设我有一个普通的外键列,如下所示:
[Table("Thing")]
public class Thing
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid? Id { get; set; }
public Guid? StatusId { get; set; }
// want to omit this potentially large object
[ForeignKey("StatusId")]
public ThingStatus Status { get; set; }
// This column isn't in the Thing table; how to best populate it from ThingStatus?
public string StatusName { get; set; }
...
}
[Table("ThingStatus")]
public class ThingStatus {...}
现在让我们假设ThingStatus有很多列,比我想要的更多。 是否有一种巧妙的方法可以通过模型注释仅检索某些值? 例如,除了拥有ThingStatus的导航属性外,还有没有办法告诉EF我的属性StatusName仅检索ThingStatus.Name?
假设没有,是否有比通过.Select从ThingStatus检索并将其映射到代码中更优雅的方法呢?
您可以通过选择一个对象来实现所需的效果。 EF只会返回您要求它选择的内容。
var results = myContext.Things
.Select(x => new ThingViewModel()
{
StatusName = x.ThingStatus.Name
})
.ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.