Mapping unconventional one-to-many relationship in EntityFramework - c#

I'm trying to code my object relationships with my database using EntityFramework (EFCore 5). My database has an unconventional many-to-many relationship. We have a Store table which has an integer ID primary key and related fields (name, et cetera), Customer, which has an ID primary key, a name, and other related fields.
Our StoreCustomer join table schema is the odd part. The join table has StoreID which points to a single Store, but instead of CustomerID, it is 'Customer Name'. It's not a one-to one relationship from StoreCustomer to Customer, because multiple Customers can have the same name. This is intended by the schema. Thus StoreCustomer to Store is a one-to-many relationship. My classes are laid out like so:
public partial class StoreCustomer
{
[Column("Store ID")]
public long StoreId { get; set; }
[Column("Customer Name")]
public string CustomerName { get; set; } = null!;
[Column]
public long Order { get; set; }
[ForeignKey(nameof(CustomerName))]
public ICollection<Customer> Customers { get; set; } = null!;
}
public partial class Customer
{
[Key]
[Column("Customer ID")]
public long CustomerId { get; set; }
[Column]
public string Name { get; set; } = null!;
}
And my OnModelCreating looks like this:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<StoreCustomer>(entity =>
{
entity.HasKey(entity => new { entity.StoreId, entity.CustomerName, entity.Order });
entity.HasMany(sc => sc.Customers)
.WithOne()
.HasPrincipalKey(sc => sc.CustomerName);
});
modelBuilder.Entity<Customer>(entity =>
{
entity.Property(e => e.CustomerId).ValueGeneratedNever();
});
OnModelCreatingPartial(modelBuilder);
}
The issue is, when I call 'context.StoreCustomers.Include(sc => sc.Customers);', the resulting query has an extra column "Customer"."CustomerName" which of course causes an exception. It's like EFCore is creating a new ghost property for this column and I don't understand why. Why is it doing this? Also, in the future when weird stuff like this happens, are there ways to debug EF to catch it in the act so I understand why it's doing what it's doing?
EDIT: Sorry, I almost forgot to mention - I am using MS Access, so I am using the unofficial EntityFrameworkCore.Jet libraries to access it. I'm not sure if that has anything to do with it, but it is the reason I am using EFCore 5, because the library doesn't support 6 yet.

Related

Entity Framework : Invalid column name *_ID even with fluent api or data annotations

Odd issue that I've been looking at all day. I am working with Entity Framework 6. The issue I have is that I have three entities:
public partial class Order : ILocationBearingObject
{
public int Id { get; set; }
// other properties and relationships here
public int? OrderProfileId { get; set; }
public int OrderTemplateId { get; set; }
public virtual OrderProfile Profile { get; set; } // optional property
public virtual OrderTemplate OrderTemplate{ get; set; }
}
public class OrderProfile
{
public int Id { get; set; }
// other properties
// added here 6/15/2021
public virtual OrderTemplate OrderTemplate{ get; set; }
}
public class OrderTemplate : EntityMetaData
{
public int Id { get; set; }
// other properties
public int? OrderProfileId{ get; set; }
public OrderProfile OrderProfile { get; set; }
}
In our model builder, we have these definitions:
modelBuilder.Entity<Order>()
.HasOptional(x => x.OrderProfile)
.WithMany(x => x.Orders)
.HasForeignKey(x => x.OrderProfileId);
modelBuilder.Entity<OrderProfile>()
.HasOptional(x => x.OrderTemplate)
.WithOptionalPrincipal(x => x.OrderProfile);
But even with the above fluent api model, we get the error
Invalid column name 'OrderProfile_Id'
Throughout various testing I was unable to find why this issue was occurring, so I looked at our logs and found when this error started popping it's head up and then was able to find the changes associated to OrderProfile and found that the only change that was made was adding the relationship from OrderProfile to OrderTemplate.
When I removed that fluent api relationship OrderProfile to OrderTemplate, it worked as expected... I don't need that relationship to OrderTemplate, but would like it to be there, how can I establish a optional 1 to optional 1 relationship without breaking other relationships? Also, why would additional relationships be effected by this?
UPDATE 6/15/2021
So I found I had a reverse navigation property in the OrderProfile model:
public virtual OrderTemplate OrderTemplate{ get; set; }
removing that and the associated fluent relationship
modelBuilder.Entity<OrderProfile>()
.HasOptional(x => x.OrderTemplate)
.WithOptionalPrincipal(x => x.OrderProfile);
Doing the above resolved the issue, but for some reason, the issue seems to have cascaded down to another relationship that has a circular reference like the above. The Order class is involved with this cascaded issue. I guess this is a pretty big cause for concern since this application worked fine for the last 4 years and for these relationships to be decaying like this is worrisome. Does anyone know why this is happening?
if you use the right naming convention, EF will do magic. in this sample, you don't need fluent API to relate entities.
public partial class Order : ILocationBearingObject
{
public int Id { get; set; }
public int? OrderProfileId { get; set; } //means HasOptional (nullable) and ForeignKey
//variable name must be OrderProfile not Profile
public virtual OrderProfile OrderProfile { get; set; }
}
public class OrderProfile
{
public OrderProfile()
{
Orders = new HashSet<Order>();
}
public int Id { get; set; }
//be aware circular reference at any conversion or mapping
public virtual ICollection<Order> Orders {get; set;} //means WithMany
}
I've got an error like this too. It's caused by unmatching OrderProfileId property in OrderTemplate class with the fluent api model
If I'm not wrong, you want the OrderProfile model a many to many relation between Order and OrderTemplate. Then if it was the case, add the nvaigation property in OrderProfile.
public class OrderProfile
{
public int Id { get; set; }
// other properties
public virtual ICollection<Order> Orders { get; set; }
public virtual OrderTemplate OrderTemplate { get; set; }
}
Then change the fluent api model to be like this
// the EF has modelled the relation for normal 1 to many relation
// modelBuilder.Entity<Order>()
// .HasOptional(x => x.OrderProfile)
// .WithMany(x => x.Orders)
// .HasForeignKey(x => x.OrderProfileId);
modelBuilder.Entity<OrderTemplate>()
.HasOptional(x => x.OrderProfile)
.WithOptional(x => x.OrderTemplate);
You're working database-first, which always leaves room for a mismatch between the actual database model and the model EF infers from class and property names and mapping code (= conceptual model). If this happens, it may help to make EF generate a database from the conceptual model and see where it creates the column it expects, OrderProfile_Id.
This is what you'll see when logging the SQL statements:
CREATE TABLE [dbo].[OrderTemplates] (
[Id] [int] NOT NULL IDENTITY,
[OrderProfileId] [int],
[OrderProfile_Id] [int],
CONSTRAINT [PK_dbo.OrderTemplates] PRIMARY KEY ([Id])
)
...
ALTER TABLE [dbo].[OrderTemplates]
ADD CONSTRAINT [FK_dbo.OrderTemplates_dbo.OrderProfiles_OrderProfile_Id]
FOREIGN KEY ([OrderProfile_Id]) REFERENCES [dbo].[OrderProfiles] ([Id])
There you see the expected nullable column OrderProfile_Id which is the FK to OrderProfiles. It's noteworthy to see that EF does not use OrderProfileId as a foreign key field. It's just a field that could be used for anything.
That's because EF6 doesn't support 1:1 associations as foreign key associations (reference property and primitive FK property).
Knowing this, the remedy is simple: remove the property OrderTemplate.OrderProfileId and tell EF to use the field OrderTemplate.OrderProfileId in the database:
modelBuilder.Entity<OrderProfile>()
.HasOptional(x => x.OrderTemplate)
.WithOptionalPrincipal(x => x.OrderProfile)
.Map(m => m.MapKey("OrderProfileId"));
That said, I wonder why Order has a foreign key to OrderProfile. Isn't its OrderProfile determined by its OrderTemplate? If it's a redundant relationship it may be better to remove it.

Need help on table design with Entity Framework Core

I am developing a simple web application where a doctor is adding multiple prescription records for patients and will select multiple drugs while doing prescription. So one patient has multiple prescription and one prescription has multiple selected drugs. I have taken one another table patientrecords for reporting purpose/Normalization perspective where I am referencing patientID and PrescriptionID.
One patient --> many prescriptions --> one to many relationship
One prescriptions -> many drugs --> one to many relationship
Below is the model for patient, prescription and drugs, PatientRecord table.
While running migration, I get this error:
Error Number:1769,State:1,Class:16
Foreign key 'FK_Drugs_Prescriptions_PrescriptionID' references invalid column 'PrescriptionID' in referencing table 'Drugs'.
I am confused with explanation of one to many relationships on Microsoft website.
Can anyone help me with it?
There are two ways to configure the relationships in EF Core
Conventions :By default, a relationship will be created when there is a navigation property discovered on a type. Not applicable to many-to-many relationship
Fluent API:you start by identifying the navigation properties that make up the relationship. HasOne or HasMany identifies the navigation property on the entity type you are beginning the configuration on. HasOne/WithOne are used for reference navigation properties and HasMany/WithMany are used for collection navigation properties.
From your screenshots and the benjamin suggested, you could configure the model like below
Patient - Prescription --> one to many relationship
Prescription - Drug --> many to many relationship
public class Prescription
{
public int PrescriptionId { get; set; }
[Required]
public string Description { get; set; }
[Required]
public DateTime PrescriptionDate { get; set; }
public int PatientId { get; set; }
public Patient Patient { get; set; }
public ICollection<DrugPrescription> DrugPrescriptions { get; set; }
}
public class Drug
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public int CurrentStock { get; set; }
public int DrugCost { get; set; }
public string Description { get; set; }
public ICollection<DrugPrescription> DrugPrescriptions { get; set; }
}
//represent a many-to-many relationship by including an entity class for
//the join table and mapping two separate one-to-many relationships.
public class DrugPrescription
{
public int DrugId { get; set; }
public Drug Drug { get; set; }
public int PrescriptionId { get; set; }
public Prescription Prescription { get; set; }
}
//DbContext
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{}
public DbSet<Patient> Patient { get;set; }
public DbSet<Drug> Drug { get;set; }
public DbSet<Prescription> Prescription { get;set; }
public DbSet<PatientRecord> PatientRecord { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
#region Drug-Prescription Many-to-Many
builder.Entity<DrugPrescription>()
.HasKey(dp => new { dp.DrugId, dp.PrescriptionId });
builder.Entity<DrugPrescription>()
.HasOne(dp => dp.Prescription)
.WithMany(p => p.DrugPrescriptions)
.HasForeignKey(dp => dp.PrescriptionId)
.OnDelete(DeleteBehavior.Restrict);
builder.Entity<DrugPrescription>()
.HasOne(dp => dp.Drug)
.WithMany(d => d.DrugPrescriptions)
.HasForeignKey(dp => dp.DrugId)
.OnDelete(DeleteBehavior.Restrict);
#endregion
}
}
There are a few things that don't quite look right here. Maybe if you clean them up you'll be close to spotting where the error is.
Firstly, I'm a bit confused by your PatientRecord class. It identifies itself with a PatientRecordId and it maps to a Patient, but it doesn't add any other information, so what is it for? If you're not going to add anything to that class, I think you can remove it from the model.
Secondly, your Prescription class maps to a collection of Drugs. That's perfect because you have a one-to-many relationship between them... so why does it also have an integer DrugId property? Unless you want the Prescription class to reference the Id of one single Drug as well as the collection of Drugs, I think you should remove it. It might be confusing Entity Framework and not giving you any value.
Thirdly, your Drug class maps to one Prescription (through its properties Prescription and PrescriptionId) but why? Presumably a drug can appear on multiple prescriptions, as it could be prescribed to many people, or prescribed to the same person several times. So I think you want to remove that too and replace it with a many-to-many relationship.
Finally, if you want to have a many-to-many relationship between Prescription and Drug (and I think you will) you probably need to add a DrugPrescription class, with a Drug property and a Prescription property, to create this many-to-many mapping.
I think if you do that you'll be a lot close to your goal, and your error message will probably go away.

Entity Framework Fluent API Cannot Insert one-to-one

I am trying to insert an object into a database table with Entity Framework and using code first (fluent api). Whilst doing this I keep running into one of the following errors:
1) InvalidOperationException: A dependent property in a
ReferentialConstraint is mapped to a store-generated column. Column:
'Id'
2) Cannot insert value into identity column with IDENTITY_INSERT set
to OFF
My relationship is a one-to-one however perhaps I can rework or structure the database to accomplish what I am wanting. I have also thought about utilizing a one to zero or zone even though the other object will always be required.
So I have the following database tables mapped into these C# objects (with virtual for the mapping):
public class test
{
[Key]
public long Id { get; set; }
public DateTime ResultDate { get; set; }
public virtual test_additional test_additional { get; set; }
public virtual test_status test_status { get; set; }
}
public class test_additional
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public long TestId { get; set; } //Foreign Key to test
...
public virtual test test { get; set; }
}
public class test_status {
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public long TestId { get; set; } //Foreign Key to Test
public long TestFormId { get; set; } //this is the object I want to insert, Foreign key to the Primary key of test_form
...
public virtual test test { get; set; }
public virtual test_form test_form { get; set; } //object mapping
}
public class test_form {
[Key]
public long Id { get; set; } //Primary Key
public string FileName { get; set; }
public virtual test_status test_status { get; set; }
}
So some pretty simple objects, I've stripped members/columns that are necessary for the functionality for ease of readability.
So there are test objects that have an optional test_additional or test_status .
These are generated with a one to zero-or-one relationship. Which are working fine and I have the relationship defined as:
modelBuilder.Entity<test>()
.HasOptional(e => e.test_additional)
.WithRequired(e =>e.test);
modelBuilder.Entity<test>()
.HasOptional(e => e.test_status)
.WithRequired(e => e.test);
Now the entity I am having trouble with is the test_form, if a test_status is defined there should always be a test_form associated with that. I currently have a relationship defined as:
modelBuilder.Entity<test_form>()
.HasRequired(e => e.test_status)
.WithRequiredDependent(e => e.test_form);
In addition I have tried appending this config:
modelBuilder.Entity<test_status>()
.HasKey(e => e.TestFormId);
--
Here is a simple implementation of inserting this object in the database:
try {
test UserTest = new test { ResultDate = DateTime.Now; }
UOW.test.Insert(UserTest);
UOW.Save();
test_additional ta = new test_additional { TestId = UserTest.Id; }
test_form tf = new test_form { FileName = "Testing.pdf"; }
UOW.test_additional.Insert( ta );
UOW.test_form.Insert( tf );
UOW.Save(); //This is where it will throw that error.
test_status status = new test_status {
TestId = UserTest.Id;
TestFormId = tf.Id;
}
UOW.test_status.Insert( status );
UOW.Save();
} catch {
throw;
}
--
I have used BreakPoints before the Unit of Work saves and I can confirm that the Id in the test_form object is the default of long which is 0. So I am not setting the Identity Column explicitly. Upon removing of test_form (in the implemented method) I can insert into the test_additional category and save with no issue.
So my question is really... are my entity relationships defined correctly? Would it be smarter to use an additional One to Zero-or-One for the test_form object? Why can I not insert this simple object into my database?
I have also thought about defining the virtual test_form object in test_status as an ICollection, then I could use .HasMany(e => e.test_form).HasForeignKey(e => e.TestFormId); so it would bind to the Foreign Key even though I would only be using 1 item for the test_status.
Opinions? Am I close?
Thanks again for taking the time to read my question!
i had your problem. just do delete your database and migration files. after do it add the new migration to create the new database.

How to seed new junction table

I am using Code first in Entity framework. There are two tables in my database - Clients and Products. There is some data in it. I have added a new, junction table that has foreign keys to both of them. How should I seed that table? And will Entity framework add new rows when I add new Client or Product, because it seems that it doesn't.:
public class UserPriceList
{
public UserPriceList()
{
PriceFactor = 1M;
}
[Key]
public int UserPriceListId { get; set; }
[Index("IX_UserPrice", 1)]
public int ProductId { get; set; }
public virtual Product Product { get; set; }
[Index("IX_UserPrice", 2)]
public int ClientId { get; set; }
public virtual Client Client { get; set; }
public decimal PriceFactor { get; set; }
}
Your UserPriceList looks a lot like a junction table, but EntityFramework is not viewing it that way because you defined it as an entity with additional properties. A junction table is automatically created behind the scenes as a table with ProductId and ClientId by adding an ICollection to the Client and ICollection to the product. There is no defined model, you would interact with it by Client.Products.Add(someProduct) and it would populate the junction table behind the scenes.
To get your UserPriceList working as a junction table you could try something like this in your OnModelCreating
modelBuilder.Entity<Product>()
.HasMany(x => x.Clients)
.WithMany(x => x.Products)
.Map(x =>
{
x.ToTable("UserPriceList"); // third table is named Cookbooks
x.MapLeftKey("ProductId");
x.MapRightKey("ClientId");
});
to explicitly map UserPriceList as the junction table. You may have problems with the non nullable decimal (or maybe not since you're setting a value in the constructor) and with having the UserPriceList defined as an entity.
Your could also just interact with the UserProductList as an entity and explicitly add items to it.
Probably the safest (as in most likely to work) way to go would be to remove the ICollection<Product> from Client and the ICollection<Client> from product add an ICollection<UserPriceList> to both.

EF5 Many to Many join table fluent API

Do I have to create a POCO class to represent a join table in a many to many relationship?
This is my scenario:
public class Event
{
public int EventId { get; set; }
public int OrganizerId { get; set; }
}
public class Person
{
public int PersonId { get; set; }
ICollection<Event> Events { get; set; }
}
public class Company
{
public int CompanyId { get; set; }
ICollection<Event> Events { get; set; }
}
Both a Person or a Company can organize an event, I thought to create a join table like
Table Events_People
PersonId
OrganizerId
Table Events_Companies
CompanyId
OrganizerId
I know that should easy to do if I create two POCOs classes, like
public class EventPerson
{
public int EventId { get; set; }
public Person PersonId { get; set; }
}
than with Fluent API something like
modelBuilder.Entity<Person>()
// PK
.HasKey(e => e.PersonId)
// FK
.HasMany(e => e.Events)
.WithRequired(e => e.PersonId);
Is there a way to avoid two POCOs and directly tell to the API to create the join table?
Thanks
You can do Many to Many with EF yes. The bigger question is that a good idea. For example you may find you have issues with cascade delete if you do and you need or want that. If you end up with 2 required relationships to the same entity ( not necessarily your specific sample code) but more generically matched to your question, then you can get EF compile/runtime errors unless you use WillCascadeOnDelete(false). Just in case people think, you can so therefore do it. Becareful.:-)
But you asked can you tell EF to create a Join
Did you not see a join table generated by EF ? I would have expected that. Im curious why not.
You can explicitly manage it:
HasMany(t => t.NavigationProperty1)
.WithMany(a => a.ReverseNavigationProperty)
.Map(c => c.ToTable("TheJoinTable"));
// rename keys as required, may not be required...
c.MapLeftKey("ColumnKeyName");
c.MapRightKey("ABetterName2");
BTW the example you suggest is exactly a pattern that is required to get around some CascadeOnDelete issues.

Categories

Resources