It’s common to want to connect to a database when building microservices and REST APIs using ASP.NET Core and Entity Framework Core. It’s also common to have relationships between database entities. One of the most common relationships is one-to-many. This relationship describes having 1 entity with multiple associated entities. In this tutorial, we’ll go over building Entity Framework Core One-to-Many Relationships using a User model and Blog Posts model as the related entities. Also please take the time to check out the video tutorials as well to get examples of full applications built using ASP.NET Core and SPAs like React and Angular.

Entity Framework One-To-Many Model Relationships

One of the first things that we’re going to do is create our Post model. This represents the number of posts that our user will own. We will reference the User Model as the Author property in the model.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ASPCoreRelationships.Models
{
    public class Post
    {
        public int PostId { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
        public ApplicationUser Author { get; set; }
        public List<PostCategory> PostCategories { get; set; }
    }
}

In our User model, we’ll create a property that represents the collection of Posts that the user owns.

using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ASPCoreRelationships.Models
{
    public class ApplicationUser : IdentityUser
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Address Address { get; set; }
        public ICollection<Post> Posts { get; set; }

    }
}

Creating the EF Core One-Many-Relationship

When trying to associate the Author and the Post, this can be done one of two ways. Getting the Author and adding Post entity to its collection or posts or getting the Post adding the user to its author property. Here are both examples.

        [Authorize]
        [HttpPost]
        public async Task<ActionResult<Post>> PostPost(Post post)
        {
            var user = await _userManager.FindByIdAsync(User.FindFirstValue(ClaimTypes.NameIdentifier));
            post.Author = user;
            _context.Posts.Add(post);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetPost", new { id = post.PostId }, post);
        }
[Authorize]
        [HttpPost]
        public async Task<ActionResult<Post>> PostPost(Post post)
        {
            var user = await _userManager.FindByIdAsync(User.FindFirstValue(ClaimTypes.NameIdentifier));
            user.Posts.Add(post);
            await _userManager.UpdateAsync(user);
            await _context.SaveChangesAsync();
            return CreatedAtAction("GetPost", new { id = post.PostId }, post);
        }

 

Retrieving Related Entities Using LINQ

Now that you’re able to save those entities to the DB, you should now be able to retrieve them. This can be done by including the related entity in your LINQ-Entities query. The Include() method allows you to get the associated entity in EF Core.

[HttpGet]
        public async Task<ActionResult<IEnumerable<Post>>> GetPosts()
        {
            return await _context.Posts.Include(a => a.Author).ToListAsync();
        }

 

Conclusion

Creating One-Many Associations in EF Core are simple. These can be handled by just using properties on the Entity and then creating the associated query in LINQ. If you’re interested in learning more, please sign up for our codebrains.io videos or check out the official Microsoft Documentation.

Codebrains Newsletter

Get weekly dev news and tutorials.

Powered by ConvertKit