Related Entity Query - code-first

I have a database with thee tables - Organisations, Locations and OrganisationLocations for example. Organisations holds information on companies, Locations holds information on offices address, and OrganisationLocations holds the many-to-many relationship info about the companies and their addresses. For example Company A might be locations X and Y, Company B might be in locations Y and Z.
These are the generated classes
public partial class Locations
{
public Locations()
{
OrganisationLocations = new HashSet<OrganisationLocations>();
}
public long Id { get; set; }
public string Description { get; set; }
public string City { get; set; }
public string Street { get; set; }
public string PostCode { get; set; }
public string Name { get; set; }
public virtual ICollection<OrganisationLocations> OrganisationLocations { get; set; }
}
public partial class Organisations
{
public Organisations()
{
OrganisationLocations = new HashSet<OrganisationLocations>();
}
public long Id { get; set; }
public string Name { get; set; }
public string Owner { get; set; }
public string ContactName { get; set; }
public string Email { get; set; }
public string Telephone { get; set; }
public virtual ICollection<OrganisationLocations> OrganisationLocations { get; set; }
}
public partial class OrganisationLocations
{
public long Id { get; set; }
public long OrganisationId { get; set; }
public long LocationId { get; set; }
public virtual Locations Location { get; set; }
public virtual Organisations Organisation { get; set; }
}
The DB Context looks like this:
public class PfApiContext : DbContext
{
public PfApiContext(DbContextOptions<PaymentAPIContext> options)
: base(options)
{
}
public DbSet<Locations> Locations { get; set; }
public DbSet<Organisations> Organisations { get; set; }
public virtual DbSet<OrganisationLocations> OrganisationLocations { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<OrganisationLocations>(entity =>
{
entity.HasOne(d => d.Location)
.WithMany(p => p.OrganisationLocations)
.HasForeignKey(d => d.LocationId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_84m7dbl1gv1p6tg1wquwm8j5u");
entity.HasOne(d => d.Organisation)
.WithMany(p => p.OrganisationLocations)
.HasForeignKey(d => d.OrganisationId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_r0mkkndb6c2tr9nl0rgjm068t");
});
}
}
How would I get, for example, all the company data for all the companies in Location X? At the point I'm querying this I actually know the LocationID, so the SQL would be
SELECT * FROM [dbo].[Organisations] WHERE Id IN (SELECT [OrganisationId] FROM [dbo].[OrganisationLocations] WHERE [LocationId] = 1)
This is probably really simple and I'm just being stupid, but I'm new to EFCore and LINQ, and the syntax of this has me scratching my head.
Selecting locations based on a location name I can understand
var locationUsers = await _pfApiContext.UserLocations.Where
(o => o.LocationName == locationName).ToListAsync();
but this is confusing me something terrible.
Thanks for any help

I would remove the virtual collections and objects from all three classes and then remove the Id field (assuming it's the primary key) in the OrganisationLocations table. The OrganisationId and the LocationId fields in the OrganisationLocations should be both the primary keys and the foreign keys in order to make it a many-to-many relationship between OrganisationLocations, Locations, and Organisation. Then you can use Linq to do a simple join query to get the info you're looking for. For example:
var orgs = (from ol in PfApiContext.OrganisationLocations
inner join o in PfApiContext.Organisation on o.Id equals ol.OrganisationId
inner join l in PfApiContext.Locations on ol.LocationId equals l.Id
where ol.LocationId = 1
select new Organisation()
{
Id = o.Id,
Name = o.Name,
Owner = o.Ower,
etc...
}

Related

Entity Framework 6 A dependent property in a ReferentialConstraint is mapped to a store-generated column. Error

I have 2 entities configured using Entity Framework 6.
Both entities have Identity on for generating primary keys on insert.
When i try adding new customer I get following error.
A dependent property in a ReferentialConstraint is mapped to a store-generated column. Column: 'Id'.
My assumption is that I did not configured one of the entities properly for one to one relationships.
public class Customer : IdEntity
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Guid? BalanceId { get; set; }
public DateTime? Dob { get; set; }
public DateTime CreateDate { get; set; }
public CustomerBalance Balance { get; set; }
public Address Address { get; set; }
public virtual ICollection<Email> Emails { get; set; } = new List<Email>();
public virtual ICollection<Phone> Phones { get; set; } = new List<Phone>();
public virtual ICollection<Reward> Rewards { get; set; }
public ICollection<Call> Calls { get; set; }
}
Here is mapping for Customer
public class CustomerConfiguration : EntityTypeConfiguration<Customer>
{
public CustomerConfiguration()
{
ToTable(nameof(Customer));
HasKey(x => x.Id).Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
HasMany(x => x.Phones);
HasMany(x => x.Emails);
HasOptional(x => x.Balance);
HasRequired(x => x.Address).WithRequiredDependent(x=>x.Customer);
}
}
Here is Address Entity
public class Address : IdEntity
{
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string Country { get; set; }
public int CustomerId { get; set; }
public virtual Customer Customer { get; set; }
}
And mapping
public class AddressConfiguration : EntityTypeConfiguration<Address>
{
public AddressConfiguration()
{
ToTable(nameof(Address));
HasKey(x => x.Id, e => e.IsClustered())
.Property(x => x.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
}
Here is a code how i insert new customer
var customer = new Customer
{
FirstName = request.FirstName,
LastName = request.LastName,
CreateDate = DateTime.Now,
Address = new Address()
};
if (!string.IsNullOrEmpty(request.Email))
customer.Emails.Add(new Email { EmailName = request.Email, IsPrimary = true });
if (!string.IsNullOrEmpty(request.Phone))
customer.Phones.Add(new Phone { Number = request.Phone, IsPrimary = true });
_repository.AddOneAsync(customer);
await _repository.Context.SaveChangesAsync();
Error is happening on save changes.
Address and Customer are one to one relationship.
Here is how my tables are configured at SQL
https://ibb.co/cYYphbJ
https://ibb.co/LnXcsyB
One-to-One relationships in EF6 must use the same keys. EG Address.CustomerId would have to be its key.
Either allow customers to have multiple addresses in the model, or change the key of Address to be CustomerID.

How to create multiple Many-to-Many relationships using the same join table [EF7/Core]

Is it possible to create 2 M:M relationships using the same join table?
I have the following situation and am receiving the exception:
Unhandled Exception: System.InvalidOperationException: Cannot create a relationship between 'ApplicationUser.ExpertTags' and 'UserTag.User', because there already is a relationship between 'ApplicationUser.StudyTags' and 'UserTag.User'. Navigation properties can only participate in a single relationship
In Tag:
public class Tag {
public Tag() {
Users = new List<UserTag>();
}
public int TagId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public ICollection<UserTag> Users { get; set; }
In ApplicationUser:
public class ApplicationUser : IdentityUser
{
public ApplicationUser()
{
StudyTags = new HashSet<UserTag>();
ExpertTags = new HashSet<UserTag>();
}
public string FirstName { get; set; }
public string LastName { get; set; }
public string Location { get; set; }
public ICollection<UserTag> StudyTags { get; set; }
public ICollection<UserTag> ExpertTags { get; set; }
}
In UserTag (CLR join):
public class UserTag
{
public string UserId { get; set; }
public ApplicationUser User { get; set; }
public int TagId { get; set; }
public Tag Tag { get; set; }
}
In ApplicationDbContext:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<UserTag>()
.HasKey(x => new { x.UserId, x.TagId });
modelBuilder.Entity<UserTag>()
.HasOne(ut => ut.User)
.WithMany(u => u.StudyTags)
.HasForeignKey(ut => ut.UserId);
modelBuilder.Entity<UserTag>()
.HasOne(ut => ut.User)
.WithMany(u => u.ExpertTags)
.HasForeignKey(ut => ut.UserId);
modelBuilder.Entity<UserTag>()
.HasOne(ut => ut.Tag)
.WithMany(t => t.Users)
.HasForeignKey(ut => ut.TagId);
}
Do I need to create separate CLR classes? Something like UserStudyTag and UserExpertTag?
Thanks!
Step down to SQL DB. You want to have table UserTag with one UserId field. How EF should guess, which records in this table are related to StudyTags and which to ExpertTags collections?
You should duplicate something.
Either split UserTag to two tables (UserStudyTag and UserExpertTag), or make two UserId fields in UserTag, say ExpertUserId and StudyUserId. Both nullable, with only one having some value in each record.

N to M relationship code first does not create the foreign key on the M-table

A SchoolclassCode can have many Pupils.
A Pupil can belong to many SchoolclassCodes.
This is an N to M relation.
I thought N to M relation work in code first by default.
But I also explicitly create the N to M relation here:
modelBuilder.Entity<SchoolclassCode>().
HasMany(c => c.Pupils).
WithMany(p => p.SchoolclassCodes).
Map(
m =>
{
m.MapLeftKey("SchoolclassCodeId");
m.MapRightKey("PupilId");
m.ToTable("SchoolclassCodePupil");
});
public class SchoolclassCode
{
public SchoolclassCode()
{
Pupils = new HashSet<Pupil>();
Tests = new HashSet<Test>();
}
public int Id { get; set; }
public string SchoolclassCodeName { get; set; }
public string SubjectName { get; set; }
public int Color { get; set; }
public string ClassIdentifier { get; set; }
public ISet<Pupil> Pupils { get; set; }
public ISet<Test> Tests { get; set; }
public Schoolyear Schoolyear { get; set; }
public int SchoolyearId { get; set; }
}
public class Pupil
{
public Pupil()
{
PupilsTests = new HashSet<PupilTest>();
SchoolclassCodes = new HashSet<SchoolclassCode>();
}
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Postal { get; set; }
public string City { get; set; }
public string Street { get; set; }
public ISet<PupilTest> PupilsTests { get; set; }
public ISet<SchoolclassCode> SchoolclassCodes { get; set; }
}
On the Pupil Table no foreign key is created at all, Why this?
For a many to many relationship, there is no foreign key on either side. The foreign keys are on the join table, which you have mapped to the table SchoolclassCodePupil:
modelBuilder.Entity<SchoolclassCode>().
HasMany(c => c.Pupils).
WithMany(p => p.SchoolclassCodes).
Map(m =>
{
m.MapLeftKey("SchoolclassCodeId");
m.MapRightKey("PupilId");
m.ToTable("SchoolclassCodePupil");
});
Entity Framework uses that junction table to determine what belongs in the somePupil.SchoolclassCodes set.

EF 4.0 - CodeFirst One To Many - Fluent API

I have the following two classes:
public class Person
{
public int Id { get; set; }
public string FullName { get; set; }
}
public class Trip
{
public int Id { get; set; }
public string Name { get; set; }
public virtual IEnumerable<Person> Persons { get; set; }
}
As you can see, a Trip can have 1 or more Persons...
I tried to use the EntityConfiguration to build the database properly but I cannot manage to make it work... I am quite confused on its usage:
public class TripConfiguration : EntityTypeConfiguration<Trip>
{
internal TripConfiguration()
{
// ???
}
}
What do I need to write to have the application to behave properly:
I need at least one person.
I might have more that one person
A person cannot be in the SAME trip twice
A person can be in more than one trip
Try this:
this.HasRequired(x => x.Person)
.WithMany(x => x.Trips)
.HasForeignKey(x => x.PersonId);
Your classes:
public class Person
{
public int Id { get; set; }
public string FullName { get; set; }
public virtual ICollection<Trip> Trips { get; set;}
}
public class Trip
{
public int Id { get; set; }
public string Name { get; set; }
public int PersonId { get; set; }
public virtual Person Person { get; set; }
}
And as far that I know, EF doesn't support unique FK (or correct me if I'm wrong..). So you have to check it yourself.
This is not a One-To-Many relationship, this is a Many-To-Many relationship, you need to have collections on both sides of the relationship. EF will create the joiner table on your behalf. Since today you cannot configure a person being in a trip only once you will need to create a unique constraint in your joiner table once is created to assure this happens since EF does not yet support Unique Key constraints through configuration.
public class Person
{
public int Id { get; set; }
public string FullName { get; set; }
public virtual ICollection<Trip> Trips { get; set; }
}
public class Trip
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Person> Persons { get; set; }
}
then
class PersonConfiguration : EntityTypeConfiguration<Person>
{
public PersonConfiguration()
{
this.HasMany(t => t.Trips).WithMany(t => t.Persons);
}
}

M:M Mapping - EF 4.3 CodeFirst (Existing Database)

I have two tables (Table A, Table B) joined with a join table (TableAB) with 3 payload columns. By Payload I mean columns apart from Id, TableAId, and TableBId.
I can insert into all tables successfully, but I need to insert data into one of the payload columns on Insert. I'm using EF 4.3, Fluent API. Can anyone help? Thanks in advance.
public class Organisation : EntityBase<int>, IAggregateRoot
{
public string Name { get; set; }
public string Url { get; set; }
public int CountryId { get; set; }
public int? OwnershipTypeId { get; set; }
public int OrganisationStatusId { get; set; }
public virtual ICollection<Feature> Features { get; set; }
public virtual ICollection<OrganisationType> OrganisationTypes { get; set; }
public virtual ICollection<PricePlan> PricePlans { get; set; }
public virtual ICollection<User> Users { get; set; }
}
public class User: EntityBase<Guid>, IAggregateRoot
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string JobTitle { get; set; }
public int? PhoneCallingCodeId { get; set; }
public int? PhoneAreaCode{ get; set; }
public string PhoneLocal { get; set; }
public int? MobileCallingCodeId { get; set; }
public int? MobileAreaCode { get; set; }
public string MobileLocal { get; set; }
public virtual ICollection<Organisation.Organisation> Organisations { get; set; }
}
public class OrganisationUser : EntityBase<int>, IAggregateRoot
{
public DateTime StartDate { get; set; }
public DateTime? EndDate { get; set; }
public int OrganisationRoleId {get; set;}//Foreign Key - have tried leaving it out, tried it as public virtual Organisation Organisation {get;set;
public bool IsApproved { get; set; }
}
public class SDContext : DbContext
{
public ObjectContext Core
{
get
{
return (this as IObjectContextAdapter).ObjectContext;
}
}
public IDbSet<User> User { get; set; }
public IDbSet<Organisation> Organisation { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Organisation>().HasMany(u => u.Users).WithMany(o => o.Organisations).Map(m =>
{
m.MapLeftKey("OrganisationId");
m.MapRightKey("UserId");
m.ToTable("OrganisationUser");
});
//I have tried specifically defining the foreign key in fluent, but I really need to understand how I can add the payload properties once I access and edit them.
Your mapping is not correct for your purpose. If you want to treat OrganisationUser as an intermediate entity between Organisation and User you must create relationships between Organisation and OrganisationUser and between User and OrganisationUser, not directly between Organisation and User.
Because of the intermediate entity which contains its own scalar properties you cannot create a many-to-many mapping. EF does not support many-to-many relationships with "payload". You need two one-to-many relationships:
public class Organisation : EntityBase<int>, IAggregateRoot
{
// ...
// this replaces the Users collection
public virtual ICollection<OrganisationUser> OrganisationUsers { get; set; }
}
public class User : EntityBase<Guid>, IAggregateRoot
{
// ...
// this replaces the Organisations collection
public virtual ICollection<OrganisationUser> OrganisationUsers { get; set; }
}
public class OrganisationUser : EntityBase<int>, IAggregateRoot
{
public int OrganisationId { get; set; }
public Organisation Organisation { get; set; }
public Guid UserId { get; set; }
public User User { get; set; }
// ... "payload" properties ...
}
In Fluent API you must replace the many-to-many mapping by the following:
modelBuilder.Entity<Organisation>()
.HasMany(o => o.OrganisationUsers)
.WithRequired(ou => ou.Organisation)
.HasForeignKey(ou => ou.OrganisationId);
modelBuilder.Entity<User>()
.HasMany(u => u.OrganisationUsers)
.WithRequired(ou => ou.User)
.HasForeignKey(ou => ou.UserId);
Your derived DbContext may also contain a separate set for the OrganisationUser entity:
public IDbSet<OrganisationUser> OrganisationUsers { get; set; }
It's obvious now how you write something into the intermediate table:
var newOrganisationUser = new OrganisastionUser
{
OrganisationId = 5,
UserId = 8,
SomePayLoadProperty = someValue,
// ...
};
context.OrganisastionUsers.Add(newOrganisastionUser);
context.SaveChanges();
If you want to make sure that each pair of OrganisationId and UserId can only exist once in the link table, it would be better to make a composite primary key of those two columns to ensure uniqueness in the database instead of using a separate Id. In Fluent API it would be:
modelBuilder.Entity<OrganisationUser>()
.HasKey(ou => new { ou.OrganisationId, ou.UserId });
More details about such a type of model and how to work with it is here:
Create code first, many to many, with additional fields in association table