c# - EF : Include navigation property to result of adding entity in DbSet

标签 c# asp.net-mvc entity-framework

我正在向我的 DataContext 添加一个实体。在此之后,我必须将此实体发送回 View (向最终用户显示结果)。

DbSet 有 Add返回新实体的方法。但我需要我的实体包含导航属性。

目前,我再次调用 DataContext 并传递 newEntity 的 Id 以查找实体。

public async Task<Entity> AddAsync(Entity entity)
{
    var savedEntity = m_DataContext.Entities.Add(entity);
    await m_DataContext.SaveChangesAsync();
    return await m_DataContext.Entities
        .Include(p=>p.SubEntity)
        .FirstAsync(p=>p.Id==savedEntity.Id);
}

是否可以在添加操作期间包含导航属性?

我的代码有效,但我正在寻找更优雅的方法。

最佳答案

注意

我意识到这不是代码的实际解决方案。然而,这是对 OP 问题的一般解决方案。

替代设计理念

如果用户输入了该实体的信息,并且它只是被持久化回数据库,那么您不需要将该对象发送回给用户。

如果通知 UI 成功持久化,然后通过另一个请求从导航属性请求新数据,那就更好了。

“成功持久化” 可以只是新添加实体的新 ID。这将使您的 AddAsync 执行 return entity.Id。在我看来,您在 AddAsync 方法的当前实现中违反了 SRP。我的例子:

public async Task<Entity> AddAsync(Entity entity)
{
    var savedEntity = m_DataContext.Entities.Add(entity);

    await m_DataContext.SaveChangesAsync();

    return entity.Id;
}

过早的优化

@CallumLinington I thought about this way. And it looks organically according to single responsibility pattern. But I have the list of entities with possibility to view them (master-detail pattern). Moreover, in first I just added a created on the view entity to this list (when received the successful call back that entity was added). But it didn't look safely for me. From another hand, I want to limit calls to the database. It is the reason for implementation in this way

除非有真正的理由表明它不安全,而不仅仅是您的意见,如果有真正的理由您想限制对数据库的调用而不仅仅是您的意见,我不会限制您的设计

在你甚至完全证明原因之前就对自己施加不必要的限制只会在以后产生糟糕的代码,并且你最终不得不“破解”一些东西,因为你的设计有缺陷。

过早的优化是一种不好的做法 - 经过深思熟虑和合理的优化是一种很好的做法。

因此,例如,仅仅因为您认为它会节省执行速度而使用静态方法而不是实例方法是不好的。

首先编写最简单的方法,然后查看实际需要优化的地方。 - 这几乎是 TDD 方法。

关于c# - EF : Include navigation property to result of adding entity in DbSet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35982572/

相关文章:

c# - 如何在 EF6 中使用临时表

c# - 扩展 VS2010 表单设计器上下文菜单

javascript - 将 viewbag 转换为 javascript 数组

asp.net-mvc - Visual Studio 2010 完整版和 ASP.NET MVC 2.0 模板

asp.net - 如何将 DateTime 值发布到 Web API 2 Controller

c# - 模拟 DbContext.set<T>.Add() EF6

c# - 无法在 Visual Studio 2010 IDE 中添加启用 HTTPS 的 WCF 服务作为服务引用

c# - 中止包含永无止境的库方法的任务(无法检查取消请求)

c# - 按字符串属性 C# 对对象列表进行排序

entity-framework - 在 EF 4.3 中使用参数执行存储过程时,对象类型 System.Collections.Generic.List 不存在映射