Currently when I want to select accounts with related properties, I have to include them manually everytime I select data:
public async Task<List<AccountDataModel>> GetAccountsAsync()
{
return await _dbContext.Accounts.Include(a => a.Settings).ToListAsync();
}
public Task<AccountDataModel> GetAccountByLoginAsync(string login)
{
return Task.FromResult(_dbContext.Accounts.Include(a => a.Settings).Where(a => a.Login.Equals(login)).FirstOrDefault());
}
Data models:
public class AccountDataModel
{
public string Id { get; set; }
public string Login { get; set; }
public string Password { get; set; }
public DateTime Created { get; set; }
public SettingsDataModel Settings { get; set; } = new SettingsDataModel();
}
public class SettingsDataModel
{
public string Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public AccountDataModel Account { get; set; }
}
Relation setting:
modelBuilder.Entity<AccountDataModel>(e =>
{
// Set primary key
e.HasKey(a => a.Id);
// Settings one-to-one relationship
e.HasOne(a => a.Settings)
.WithOne(s => s.Account)
.OnDelete(DeleteBehavior.Cascade)
.HasForeignKey<SettingsDataModel>(s => s.Id)
.IsRequired();
});
I was wondering, if this is possible to automatically load related Settings property for each Account selected?
I'm using the lastest version of EF Core.
Related
For context, I'm in the process of migrating our EF6 Db Context to EF Core 3. Why EF Core 3 only? Currently we're not able to upgrade to the latest EF Core version because of project constraints. We're still using .NET Framework 4.5.6, we're slowly upgrading.
Libaries used
EF Core 3.1.19
Devart.Data.MySql.Entity.EFCore 8.19
The models
public class AutomatedInvestigation
{
public int AutomatedSearchScreenshotId { get; set; }
public int OrderId { get; set; }
public int OrderLineItemId { get; set; }
public int ServiceId { get; set; }
public int? ComponentId { get; set; }
public OrderLineItemResults Result { get; set; }
public int? PageSourceDocumentId { get; set; }
public string Errors { get; set; } = string.Empty;
public DateTime CreateDateTime { get; set; }
public DateTime EditDateTime { get; set; }
public SearchRequestParameters SearchParameters { get; set; }
public Service Service { get; set; }
public Subject Subject { get; set; }
public Order Order { get; set; }
public OrderLineItem OrderLineItem { get; set; }
public virtual Component Component { get; set; }
}
[ComplexType]
public class SearchRequestParameters
{
public SearchRequestParameters()
{
this.Serialized = string.Empty;
}
[NotMapped]
[JsonIgnore]
public string Serialized
{
get { return JsonConvert.SerializeObject(Parameters); }
set
{
if (string.IsNullOrEmpty(value)) return;
var parameters = JsonConvert.DeserializeObject<SearchParameters>(value);
Parameters = parameters ?? new SearchParameters();
}
}
public SearchParameters Parameters { get; set; }
}
[ComplexType]
public class SearchParameters
{
public string FirstName { get; set; } = string.Empty;
public string LastName { get; set; } = string.Empty;
public DateTime DOB { get; set; }
public string State { get; set; } = string.Empty;
}
The model builder (excluded irrelevant code)
internal static ModelBuilder BuildAutomationInvestigationModel(this ModelBuilder modelBuilder)
{
var entityTypeBuilder = modelBuilder.Entity<AutomatedInvestigation>();
entityTypeBuilder.OwnsOne(s => s.SearchParameters, sa =>
{
sa.OwnsOne(p => p.Parameters, pa =>
{
pa.Property(p => p.FirstName);
pa.Property(p => p.LastName);
pa.Property(p => p.DOB);
pa.Property(p => p.State);
});
});
entityTypeBuilder.ToTable("automated_investigations")
.HasKey(p => p.AutomatedSearchScreenshotId);
entityTypeBuilder.MapProperties()
.MapRelations();
return modelBuilder;
}
private static EntityTypeBuilder<AutomatedInvestigation> MapProperties(this EntityTypeBuilder<AutomatedInvestigation> entityTypeBuilder)
{
entityTypeBuilder.Property(p => p.AutomatedSearchScreenshotId).HasColumnName("automated_investigation_id");
entityTypeBuilder.Property(p => p.OrderId).HasColumnName("order_id").IsRequired();
entityTypeBuilder.Property(p => p.OrderLineItemId).HasColumnName("order_line_item_id").IsRequired();
entityTypeBuilder.Property(p => p.ServiceId).HasColumnName("service_id").IsRequired();
entityTypeBuilder.Property(p => p.ComponentId).HasColumnName("component_id").IsRequired(false);
entityTypeBuilder.Property(p => p.Result).IsRequired();
entityTypeBuilder.Property(p => p.PageSourceDocumentId).IsRequired(false);
entityTypeBuilder.Property(e => e.Errors)
.IsRequired()
.HasColumnName("errors")
.HasColumnType("mediumtext");
entityTypeBuilder.Property(p => p.CreateDateTime).HasColumnName("create_datetime").IsRequired();
entityTypeBuilder.Property(p => p.EditDateTime).HasColumnName("edit_datetime").IsRequired();
return entityTypeBuilder;
}
The error
I've tried adding HasColumnName but throws the same error. I've also tried using [Owned] annotation instead of the OwnsOne on the model builder but throws the same error. Also tried just specifying "SearchParameters" but will throw unknown column on "Parameters".
Let's assume that Administrator, Purchaser and Supplier have User base type and remaining models look following:
public class Vendor
{
public int VendorId { get; set; }
public List<Supplier> Suppliers { get; set; }
}
public class Task
{
public int TaskId { get; set; }
public Administrator Admin { get; set; }
public List<Purchaser> Purchasers { get; set; }
public Vendor Vendor { get; set; }
}
Now I would like to create a UserTask table that contains IDs of all users of the Task: an Admin, Purchasers and Suppliers of the Vendor in column User and their Tasks IDs in column Task.
How could I configure such setup in Fluent API?
Edit:
I created additional entity UserTask that consists of IDs and navigation properties:
public class UserTask
{
public int UserId { get; set; }
public User User { get; set; }
public int TaskId { get; set; }
public Task Task { get; set; }
//some other needed properties
}
And tried to configure models like this:
modelBuilder.Entity<UserTask>(ut =>
{
ut.HasKey(x => new { x.UserId, x.TaskId });
ut.HasOne(u => u.User).WithMany()
.HasForeignKey(u => u.UserId)
.OnDelete(DeleteBehavior.Cascade);
ut.HasOne(t => t.Task).WithMany()
.HasForeignKey(t => t.TaskId)
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity<Task>(t =>
{
t.HasMany(p => p.Purchasers).WithMany(p => p.Tasks);
t.HasOne(a => a.Administrator).WithMany(); //adding a => a.Task expression in parameter throws error that the relationship is already defined
t.HasMany(s => s.Vendors.Suppliers).WithMany(s => s.Tasks); //throws error
});
And it fails because HasMany(s => s.Vendors.Suppliers) i not a valid member access expression. Is there any way to overcome this issue?
Considering the relationships in these tables, add a property so that Fluent API can reference the relationship. About the specific modelbuilder.
modelBuilder.Entity<Supplier>()
.HasOne(x => x.vendor)
.WithMany(y => y.Suppliers);
modelBuilder.Entity<Administrator>()
.HasOne(a => a.tasks)
.WithOne(t => t.Admin)
.HasForeignKey<Administrator>(f=>f.AdministratorId);
modelBuilder.Entity<Vendor>()
.HasOne(a => a.tasks)
.WithOne(t => t.Vendor)
.HasForeignKey<Vendor>(f=>f.VendorId);
The model need to be redesigned as this.
public class User
{
public int id { get; set; }
public string Property { get; set; }
}
public class Vendor
{
public int VendorId { get; set; }
public List<Supplier> Suppliers { get; set; }
public Tasks tasks { get; set; }
}
public class Tasks
{
[Key]
public int TaskId { get; set; }
public Administrator Admin { get; set; }
public List<Purchaser> Purchasers { get; set; }
public Vendor Vendor { get; set; }
}
public class Supplier:User
{
public int SupplierId { get; set; }
public string SupplierProperty { get; set; }
public Vendor vendor { get; set; }
}
public class Administrator:User
{
public int AdministratorId { get; set; }
public string adminProperty { get; set; }
public Tasks tasks { get; set; }
}
public class Purchaser:User
{
public int PurchaserId { get; set; }
public string purProperty { get; set; }
public Tasks tasks { get; set; }
}
In project I can have one User that can have many UserActivites. In my models I've set up their relationship as follows:
public class User
{
public int Id { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string Surname { get; set; }
public string Email { get; set; }
//relationship mapping example
// delete these attributes and you'll cause a self referenceing loop error
[JsonIgnore]
[IgnoreDataMember]
public List<UserActivity> Activities { get; set; }
}
public class UserActivity
{
public int Id { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public string Project { get; set; }
public DateTime EntryDate { get; set; }
// relationship mapping
public User User { get; set; }
}
And in my repository class, I'm getting all my user activities this way:
public async Task<IEnumerable<UserActivity>> GetAll()
{
var result = await _context.UserActivities.Include(activity => activity.User).OrderByDescending(x => x.EntryDate).ToListAsync();
return result;
}
However, when I run my project, the User property of UserActivities is null. So I checked the Microsoft docs on EF Core relationships and updated my OnModelCreating method inside of my context to also do the mapping as follows:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<UserActivity>().ToTable("UserActivities").Property(x => x.Id).ValueGeneratedOnAdd();
modelBuilder.Entity<UserActivity>().ToTable("UserActivities").HasOne(x => x.User).WithMany();
modelBuilder.Entity<User>().ToTable("Users").Property(x => x.Id).ValueGeneratedOnAdd();
base.OnModelCreating(modelBuilder);
}
However, when I run the project again, my User property still isn't populated. I know this isn't a data issue as I have data inside of my User table and display that on a separate page.
I'm not sure what I'm doing wrong/missing with this. So any help would be appreciated
Try this code:
Your tables:
public partial class User
{
public User()
{
UserActivities = new HashSet<UserActivity>();
}
[Key]
public int Id { get; set; }
[Required]
public string UserName { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
public string Email { get; set; }
[InverseProperty(nameof(UserActivity.User))]
public virtual ICollection<UserActivity> UserActivities { get; set; }
}
public partial class UserActivity
{
[Key]
public int Id { get; set; }
public int UserId { get; set; }
public string Project { get; set; }
public DateTime EntryDate { get; set; }
[ForeignKey(nameof(UserId))]
[InverseProperty("UserActivity")]
public virtual User User { get; set; }
}
dbcontext:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<UserActivity>(entity =>
{
entity.HasOne(d => d.User)
.WithMany(p => p.UserActivities)
.HasForeignKey(d => d.UserId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_UserActivity_User");
});
OnModelCreatingPartial(modelBuilder);
}
It is my first a many-to-many relation consisting of Team, User and TeamUser objects. In TeamController I mapped TeamForCreationDto to Team, but ICollection Members was empty. Some bug in CreateMap?Q1: How it should be combined to fill all property and tables by EF? Now I have "for" loop and there created/added TeamUser.
Q2: If I must fill both property AdminId and Admin?
A2: No, after adding Admin, property AdminId in DB thanks EF will find value automatically.
public class Team
{
public int Id { get; set; }
public string Name { get; set; }
public int AdminId { get; set; }
public User Admin { get; set; }
//public int[] MembersId { get; set; }
public ICollection<TeamUser> Members { get; set; }
}
public class User
{
public int Id { get; set; }
public string Username { get; set; }
public ICollection<Team> TeamsAsAdmin { get; set; }
public ICollection<TeamUser> TeamsAsMember { get; set; }
}
public class TeamUser
{
public int TeamId { get; set; }
public Team Team { get; set; }
public int UserId { get; set; }
public User User { get; set; }
}
Relations between tables in ModelBuilder
builder.Entity<Team>()
.HasOne(t => t.Admin)
.WithMany(u => u.TeamsAsAdmin)
.OnDelete(DeleteBehavior.Restrict);
builder.Entity<TeamUser>()
.HasKey(tu => new { tu.TeamId, tu.UserId });
builder.Entity<TeamUser>()
.HasOne(tu => tu.User)
.WithMany(u => u.TeamsAsMember)
.HasForeignKey(tu => tu.UserId)
.OnDelete(DeleteBehavior.Cascade);
builder.Entity<TeamUser>()
.HasOne(tu => tu.Team)
.WithMany(t => t.Members)
.HasForeignKey(tu => tu.TeamId);
My CreateMap in AutoMapperProfiles()
CreateMap<TeamForCreationDto, Team>().ReverseMap().ForMember(u => u.MembersId, opt => opt.MapFrom(x => x.Members));
My TeamController.cs
public async Task<IActionResult> Create(int userId, TeamForCreationDto teamForCreationDto)
{
if (await _repoTeams.TeamExists(teamForCreationDto.Name))
return BadRequest("A team with this name already exists!");
var mappedTeam = _mapper.Map<Team>(teamForCreationDto);
//mappedTeam.AdminId = userId;
mappedTeam.Admin = await _repoUsers.GetUser(userId);
_repoTeams.Add(mappedTeam);
for (int i = 0; i < teamForCreationDto.MembersId.Length; i++)
{
TeamUser tm = new TeamUser();
tm.Team = mappedTeam;
tm.User = await _repoUsers.GetUser(teamForCreationDto.MembersId[i]);
_repoTeams.Add(tm);
}
await _repoTeams.SaveAll();
}
TeamForCreationDto.cs
public class TeamForCreationDto
{
int Id { get; set; }
public string Name { get; set; }
public string PhotoUrl { get; set; }
public int[] MembersId { get; set; }
}
I'm trying to make a simple app to try Entity Framework Core, but i a have problem with setting up relations between entities. My entities:
public class Card
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Adress { get; set; }
public DateTime DoB { get; set; }
public DateTime DoS { get; set; }
public User Portal { get; set; }
public List<Reservation> Res { get; set; }
}
public class Doctor
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Email { get; set; }
public TimeSpan Start_Working { get; set; }
public TimeSpan End_Working { get; set; }
public List<Reservation> Reservations { get; set; }
public int SpecID { get; set; }
public Spec Spec { get; set; }
}
public class Reservation
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public DateTime DoR { get; set; }
public string Info { get; set; }
public int CardID { get; set; }
public Card Card_Nav_R { get; set; }
public int DoctorID { get; set; }
public Doctor Doctor { get; set; }
}
public class Spec
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public List<Doctor> Doctors { get; set; }
}
public class User
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public int CardID { get; set; }
public Card Card { get; set; }
}
And a configuration class where i tried to set up relations:
class ApplicationContext:DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Card> Cards { get; set; }
public DbSet<Reservation> Reservations { get; set; }
public DbSet<Doctor> Doctors { get; set; }
public DbSet<Spec> Specs { get; set; }
public ApplicationContext()
{
Database.EnsureCreated();
}
protected override void OnModelCreating(ModelBuilder ModelBuilder)
{
ModelBuilder.Entity<User>().HasKey(u => u.Id);
ModelBuilder.Entity<Card>().HasKey(c => c.Id);
ModelBuilder.Entity<Doctor>().HasKey(d => d.Id);
ModelBuilder.Entity<Spec>().HasKey(s => s.Id);
ModelBuilder.Entity<Reservation>().HasKey(r => r.Id);
ModelBuilder.Entity<User>().Property(u => u.Email).IsRequired();
ModelBuilder.Entity<User>().Property(u => u.Password).IsRequired();
ModelBuilder.Entity<Card>().Property(c => c.Name).IsRequired();
ModelBuilder.Entity<Card>().Property(c => c.Surname).IsRequired();
ModelBuilder.Entity<Card>().Property(c => c.DoB).IsRequired();
ModelBuilder.Entity<Card>().Property(c => c.Adress).IsRequired();
ModelBuilder.Entity<Doctor>().Property(d => d.Name).IsRequired();
ModelBuilder.Entity<Doctor>().Property(d => d.Surname).IsRequired();
ModelBuilder.Entity<Doctor>().Property(d => d.Spec).IsRequired();
ModelBuilder.Entity<Doctor>().Property(d => d.Email).IsRequired();
ModelBuilder.Entity<Doctor>().Property(d => d.Start_Working).IsRequired();
ModelBuilder.Entity<Doctor>().Property(d => d.End_Working).IsRequired();
ModelBuilder.Entity<Reservation>().Property(r => r.Info).IsRequired();
ModelBuilder.Entity<Reservation>().Property(r => r.Card_Nav_R).IsRequired();
ModelBuilder.Entity<Reservation>().Property(r => r.Doctor).IsRequired();
ModelBuilder.Entity<Reservation>().Property(r => r.DoR).IsRequired();
ModelBuilder.Entity<Spec>().Property(s => s.Name).IsRequired();
ModelBuilder.Entity<Doctor>().HasOne<Spec>(d=>d.Spec).WithMany(s => s.Doctors).HasForeignKey(d => d.SpecID);
ModelBuilder.Entity<User>().HasOne<Card>(u => u.Card).WithOne(c => c.Portal).HasForeignKey<User>(u => u.CardID);
ModelBuilder.Entity<Reservation>().HasOne<Card>(r => r.Card_Nav_R).WithMany(c => c.Res).HasForeignKey(r => r.CardID);
ModelBuilder.Entity<Reservation>().HasOne<Doctor>(r => r.Doctor).WithMany(d => d.Reservations).HasForeignKey(r => r.DoctorID);
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=Simple_Try;Trusted_Connection=True;");
}
}
So, when i tried to add migration or add something to database i saw this error:
System.InvalidOperationException: 'The property or navigation 'Spec' cannot be added to the entity type 'Doctor' because a property or navigation with the same name already exists on entity type 'Doctor'.'
I really don't know how to fix this, i tried to use annotations instead of Fluent API, but had the same result.
The cause of the exception is the following line:
ModelBuilder.Entity<Doctor>().Property(d => d.Spec).IsRequired();
because Doctor.Spec is a navigation property
public class Doctor
{
// ...
public Spec Spec { get; set; }
}
and navigation properties cannot be configured via Property fluent API.
So simply remove that line. Whether reference navigation property is required or optional is controlled via relationship configuration. In this case
ModelBuilder.Entity<Doctor>()
.HasOne(d => d.Spec)
.WithMany(s => s.Doctors)
.HasForeignKey(d => d.SpecID)
.IsRequired(); // <--
although the IsRequired is automatically derived from the FK property type - since SpecID is non nullable, then the relationship is required.
For more info, see Required and Optional Properties and Required and Optional Relationships documentation topics.