[英]How to retrieve a subset of columns in a foreign-key relationship in Entity Framework with Data Annotations
Suppose I have an ordinary foreign-key column like this: 假设我有一个普通的外键列,如下所示:
[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 {...}
Now let us suppose ThingStatus has lots of columns, more than I want. 现在让我们假设ThingStatus有很多列,比我想要的更多。 Is there a slick way to retrieve only some of the values via the model annotations ? 是否有一种巧妙的方法可以通过模型注释仅检索某些值? Instead of having a navigation property to ThingStatus, is there a way to tell EF to retrieve only ThingStatus.Name for my property StatusName, for example? 例如,除了拥有ThingStatus的导航属性外,还有没有办法告诉EF我的属性StatusName仅检索ThingStatus.Name?
Assuming there's not, is there a more elegant way to get this than retrieving from ThingStatus via .Select and mapping it in code? 假设没有,是否有比通过.Select从ThingStatus检索并将其映射到代码中更优雅的方法呢?
You can accomplish the desired effect by selecting an object. 您可以通过选择一个对象来实现所需的效果。 EF will only return what you tell it to select. EF只会返回您要求它选择的内容。
var results = myContext.Things
.Select(x => new ThingViewModel()
{
StatusName = x.ThingStatus.Name
})
.ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.