EF: enable navigation property as a result of adding an object to DbSet

I am adding an object to my DataContext. After that I have to send this entity for viewing (show the result to the end user).

DbSet has an Add method that returns a new object. But I need my entity with navigation properties enabled.

Right now I am making another call to the DataContext and passing in the newEntity identifier to find the object.

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);
}

Can I enable the navigation property during an add operation?

My code works, but I'm looking for a way to do it more elegantly.

+4
source share
2 answers

NB

, . .

, , .

, , .

" " . AddAsync do return entity.Id. -, SRP AddAsync. :

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

    await m_DataContext.SaveChangesAsync();

    return entity.Id;
}

@CallumLinington . . ( master-detail). , ( , ). . , . .

, , , , , , .

, , , "" , .

- - .

, , , , , .

, , . - TDD.

0

AddAsync :

  • entity.SubEntity == null
  • entity.SubEntity!= null

entity.SubEntity null, include SubEntity.

entity.SubEntity , saveEntity.SubEntity , saveChanges, savedEntity.SubEntity .

, savedEntity, subEntity.

Entity-Framework " " " ": , .

:

public class Blog
{
    public int Id {get; set;}
    public string Name {get; set;}
    public ICollection<Post> Posts {get; set;}
}
public class Post
{
    public int Id {get; set;}
    public int BlogId {get; set;} // will become foreign key to Blog
    public virtual Blog Blog {get; set;}
    public string Text {get; set;
}
public class BlogContext : DbContext
{
    public BlogContext() : base("DbTestBlogs") {}
    public DbSet<Blog> Blogs {get; set;}
    public DbSet<Post> Posts {get; set;}
}

. (subentities). :

class Program
{
    static void Main(string[] args)
    {
        Blog blogToAdd = new Blog()
        {
            Name = "My Blog",
            Posts = new Post[]
            {
                new Post()  {Text = "My 1st Post"},
                new Post()  {Text = "My 2nd Post"},
                new Post()  {Text = "My 3rd Post"},
            },
        };
        // note: Post.BlogId and Post.Blog are not filled!

        Blog addedBlog = AddBlog(blogToAdd);
        Debug.Assert(addedBlog.Posts != null);
        Debug.Assert(addedBlog.Posts.Count() == blogToAdd.Posts.Count());
    }

    private static Blog AddBlog(Blog blogToAdd)
    {
        using (var dbContext = new BlogContext())
        {
            Blog addedBlog = dbContext.Blogs.Add(blogToAdd);
            dbContext.SaveChanges();
            return addedBlog;
        }
    }

, , Post.BlogId Post.Blog. , include

-1

All Articles