简体   繁体   English

如何在带有数据注释的实体框架中检索外键关系中的列子集

[英]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.

相关问题 在Entity Framework上创建外键关系的问题 - Problems creating a Foreign-Key relationship on Entity Framework 实体框架 - 代码优先 - 数据注释 - 不必要的外键列 - Entity Framework - Code first - Data annotations - Unnecessary foreign key columns 如何使用数据注释在实体框架中设置外键? - How to set up foreign key in Entity Framework with data annotations? 实体框架5无法更改该关系,因为一个或多个外键属性不可为空 - Entity Framework 5 The relationship could not be changed because one or more of the foreign-key properties is non-nullable 实体框架无法更改关系,因为一个或多个外键属性不可为空 - Entity Framework The relationship could not be changed because one or more of the foreign-key properties is non-nullable 我可以使用Entity Framework Code First数据注释创建双向外键关系吗? - Can I create a bidirectional foreign key relationship using Entity Framework Code First data annotations? 实体框架外键关系不返回任何数据 - Entity Framework foreign key relationship returns no data Mvc,外键关系 - Mvc, Foreign-Key Relationship 自动检索实体框架外键关系模型 - Retrieve Entity Framework Foreign Key Relationship Models automatically 实体框架 OneToMany 更新项目 - 缺少外键值 - Entity Framework OneToMany updating items - Missing foreign-key value
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM