Linking Entities in Entity Framework Core
To establish a relationship between User
and WorkingExperience
, we need to modify the entity classes as follows:
public class User
{
public int Id { get; set; }
public string UserName { get; set; }
[MaxLength(50)]
public string Email { get; set; }
public ICollection<jobexperiencie> jobexperiencies { get; set; }
}
public class jobexperiencie
{
public int Id { get; set; }
public int UserId { get; set; }
[MaxLength(50)]
public string Name { get; set; }
public string Details { get; set; }
public string Environment { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
}
In the User
class, we add an ICollection<WorkingExperience>
property. We use ICollection
to provide more versatility, allowing us to add, remove, or update elements. If these features are not needed, IEnumerable
or IList
can be suitable alternatives.
Next, we add the UserId
property to the WorkingExperience
class, which establishes the relationship between the two entities.
After making these modifications, we need to run the migrations. Once the migrations are completed, an index and a foreign key will be added to the database.
Inserting Related Data in Entity Framework Core
To insert related data, we can inject our ejemploEFContext
and use it in our code. In the following example, we first create a User
object and then associate WorkingExperience
objects with that user:
[HttpPost("InsertDataExample1")]
public async Task InsertDataExample1()
{
User user1 = new User()
{
Email = $"{Guid.NewGuid()}@mail.com",
UserName = "id1"
};
List<jobexperiencie> workingExperiences1 = new List<jobexperiencie>()
{
new jobexperiencie()
{
UserId = user1.Id,
Name = "experience 1",
Details = "details1",
Environment = "environment"
},
new jobexperiencie()
{
UserId = user1.Id,
Name = "experience 2",
Details = "details2",
Environment = "environment"
}
};
await _context.Users.AddAsync(user1);
await _context.jobexperiencies.AddRangeAsync(workingExperiences1);
await _context.SaveChangesAsync();
}
Entity Framework Core understands that the UserId
column in WorkingExperience
refers to the Id
column in the User
table. Consequently, the associated WorkingExperience
records will be inserted into the database.
Alternatively, if we have set up the relationship correctly by using ICollection<T>
in the User
entity, we can insert all the related data by simply adding it to the user object:
User user1 = new User()
{
Email = $"{Guid.NewGuid()}@mail.com",
UserName = "id1",
jobexperiencies = new List<jobexperiencie>()
{
new jobexperiencie()
{
Name = "experience 1 same object",
Details = "details1",
Environment = "environment"
},
new jobexperiencie()
{
Name = "experience 2 same object",
Details = "details2",
Environment = "environment"
}
}
};
Querying Related Data with Entity Framework Core
To query related data, we can use the .Include()
method on the DbSet
. The following example retrieves a user and includes their working experiences:
[HttpGet("{userId}")]
public async Task<User?> GetExample(int userId)
=> await _context.Users
.Include(u => u.jobexperiencies)
.FirstOrDefaultAsync(a => a.Id == userId);
By using .Include()
, we retrieve both the user and their associated working experiences in a single query.
It's important to note that excessive use of the .Include()
method can lead to performance issues. Entity Framework Core has made significant improvements in query generation, but including all related tables in every query can result in database bottlenecks. Use the .Include()
method selectively based on your specific needs.
As we wrap up this post, it's worth mentioning that in previous versions, the relationship needed to be defined in the OnModelCreating
method of the DbContext
. However, with Entity Framework Core, this step is no longer necessary.
Thank you for reading our blog post! We hope you found this information helpful in understanding how to establish entity relationships in Entity Framework Core. Stay tuned for more exciting topics and code examples in our future posts!