Entity Framework Code First adding record error - c#

Ok let me start with my model:
Contact Method Types:
public class ContactMethodType
{
[Key]
[HiddenInput(DisplayValue = false)]
public Guid ContactMethodTypeGUID { get; set; }
[Required(ErrorMessage = "Please enter a Contact Method Type Name.")]
public string Name { get; set; }
[Required(ErrorMessage = "Please enter a brief description.")]
public string Description { get; set; }
public bool IsActive { get; set; }
public virtual ICollection<ContactMethod> ContactMethods { get; set; }
Contact Methods:
public class ContactMethod
{
[Key]
[HiddenInput(DisplayValue = false)]
public Guid ContactMethodGUID { get; set; }
public virtual ContactMethodType Type { get; set; }
public string CountryCode { get; set; }
[Required]
public string Identifier { get; set; }
public bool IsPreferred { get; set; }
}
Recipient:
public class Recipient
{
[Key]
public Guid RecipientGUID { get; set; }
[Required(ErrorMessage = "Please enter a Recipient's First Name.")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Please enter a Recipient's Last Name.")]
public string LastName { get; set; }
public string Company { get; set; }
public UserGroup Owner { get; set; }
public List<ContactMethod> ContactMethods { get; set; }
public User CreatedBy { get; set; }
public DateTime CreatedOn { get; set; }
public User LastModifiedBy { get; set; }
public DateTime LastModifiedOn { get; set; }
public bool IsActive { get; set; }
}
I have two Contact Method Types already defined:
Email and SMS
Now I am creating a new Recipient, so I add all of the required data to my Recipient Object, and then I call:
context.Recipients.Add(myRecipient);
context.SaveChanges();
What I get is an error that I am tying to add a new ContactMethodType when one already exists. But this is supposed to be a one to many relationship, and I do not want to add a new ContactMethodType, just categorize a new Contact Method(s) for my recipient.
I am not sure when this is happening. Maybe my model is incorrect? Based on what is chosen as the type, I pull that Type object, and set it to the ContactMethod.Type variable. But like I said, instead of just linking it to an existing ContactMethodType, it is trying to re-create it, and since the GUID already exists, I get the error that the record cannot be created because the key (GUID) already exits.
Any ideas?

After discussing this offline with Marek, it boiled down to DbSet<TEntity>.Add(entity) assuming that all entities in the graph being added are new.
From The API docs for Add...
Begins tracking the given entity, and any other reachable entities that are not already being tracked, in the Added state such that they will be inserted into the database when SaveChanges() is called.
Because this model uses client generated keys, meaning that all entities have a key value assigned before they are given to the context, you can't use any of the "smarter" methods (such as DbSet<TEntity>.Attach(entity)) that would inspect key values to work out if each entity is new or existing.
After adding the new recipient, you can use call DbSet<TEntity>.Attach(entity) on each existing entity (i.e. the contact method type). Alternatively, DbContext.Entry(entity).State = EntityState.Unchanged will also let EF know that an entity is already in the database.
You could also look at DbContext.ChangeTracker.TrackGraph(...), see the API docs for more info.

Related

EF Core 2.2.6: Unable to map 2 foreign keys to the same table

I am having issues trying to map two fields that are foreign keys into the same table. The use case is for a modifier and creator. My class already has the Ids, and then I wanted to add the full User object as virtual.
I am using a base class so that each of my tables have the same audit fields:
public class Entity
{
public long? ModifiedById { get; set; }
public long CreatedById { get; set; } = 1;
[ForeignKey("CreatedById")]
public virtual User CreatedByUser { get; set; }
[ForeignKey("ModifiedById")]
public virtual User ModifiedByUser { get; set; }
}
The child class is very simple:
public class CircleUserSubscription : Entity
{
[Required]
public long Id { get; set; }
public long SponsorUserId { get; set; }
[ForeignKey("SponsorUserId")]
public virtual User User { get; set; }
public long TestId { get; set; }
[ForeignKey("TestId")]
public virtual User Test { get; set; }
}
This is a standard junction table.
When I try to generate the migration, I am getting errors that I don't understand fully.
Unable to determine the relationship represented by navigation property 'CircleUserSubscription.User' of type 'User'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
I tried what this answer had, but the code is basically the same: https://entityframeworkcore.com/knowledge-base/54418186/ef-core-2-2---two-foreign-keys-to-same-table
An inverse property doesn't make sense since every table will have a reference to the user table.
For reference, here is the User entity:
public class User : Entity
{
public long Id { get; set; }
public string Username { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
I am hoping you all can help me out, TIA :)
EDIT: One thing to note, all of this worked fine when the entity class was as follows:
public class Entity
{
public long? ModifiedById { get; set; }
public long CreatedById { get; set; } = 1;
}
It was only after I added the entity that things went awry.

EF Optional Relationships / Nullable / Navigation Table

I solved this, answer below.
I am new to EF and having a lot of difficulty trying to get an optional relationship. I am looking to have a relationship where I have ApiLogItem Model with an UserId property which can be null / anonymous user or a logged in user to track all Api calls. The goal is to have Existing Users who do some create a new object to be linked to that object. I do not want to create new Users every time a new ApiLogItem is created.
I have tried a dozen variations with virtual / foreign key attributes and I am stumped. It works great for null / anonymous user but once I attach an actual user to the ApiLogItem it will not insert. I get this error:
{"Violation of PRIMARY KEY constraint 'PK_AspNetUsers'. Cannot insert
duplicate key in object 'dbo.AspNetUsers'. The duplicate key value is
(09c0d2e2-b003-4be8-a62a-08d7268af58e).\r\nThe statement has been
terminated."}
I have tried following this tutorial but alas no luck.
https://www.learnentityframeworkcore.com/conventions/one-to-many-relationship#targetText=EF%20Core%20will%20create%20a,public%20class%20Author
public class ApiLogItem
{
[Key]
public long Id { get; set; }
[Required]
public int StatusCode { get; set; }
[Required]
public string Method { get; set; }
[MaxLength(45)]
public string IPAddress { get; set; }
public Guid? UserId { get; set; }
public ApplicationUser User { get; set; }
}
public class ApplicationUser : IdentityUser<Guid>
{
[MaxLength(64)]
public string FirstName { get; set; }
[MaxLength(64)]
public string LastName { get; set; }
public List<ApiLogItem> ApiLogItems { get; set; }
}
Error happens when I want to create a new ApiLogItem:
using (ApplicationDbContext _dbContext = new ApplicationDbContext(_optionsBuilder.Options))
{
_dbContext.ApiLogs.Add(apiLogItem);
await _dbContext.SaveChangesAsync();
}
I have reviewed several other stackoverflow issues and none seem to fix. You can find the repository here:
https://github.com/enkodellc/blazorboilerplate
You are calling applicationDbContextSeed.SeedDb(); in your Startup class each time you run, and in your SeedDb method, you are adding a user with a static id 09C0D2E2-B003-4BE8-A62A-08D7268AF58E.
The first time you run, it will create that user; the second time, it will fail because that user (with that id) already exists.
I figured it out. It needs a virtual in the parent and just the id in the child. I need to learn more about EF as it is not intuitive to me. Will post a better answer later today after testing.
public class ApplicationUser : IdentityUser<Guid>
{
[MaxLength(64)]
public string FirstName { get; set; }
[MaxLength(64)]
public string LastName { get; set; }
public ICollection<ApiLogItem> ApiLogItems { get; set; }
}
public class ApiLogItem
{
[Key]
public long Id { get; set; }
[Required]
public int StatusCode { get; set; }
[Required]
public string Method { get; set; }
[MaxLength(45)]
public string IPAddress { get; set; }
public Guid? UserId { get; set; }
}

Entity framework add's new record in one-to-one relation while object has an ID

I'm new to c# and I have a basic problem with saving/updating data.
With two classes :
public class User
{
public int UserId { get; set; }
public string Email { get; set; }
public string Login { get; set; }
public string Password { get; set; }
public DateTime RegisteredDate { get; set; }
public class Task
{
public int TaskId { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Comment { get; set; }
public User DeclaredBy { get; set; }
}
I'm trying to save a task object (new or updated) with DeclaredBy field set
dbContext.Tasks.AddOrUpdate(task);
dbContext.SaveChanges();
User set in DeclaredBy field has an ID, but after executing SaveChanges() a new record of User appears in DB.
This is how EF works, if you add entity with other related entity then both will be stored in DB. If you want to store only one then you need to set other navigation properties to null and only set foreign key id, which currently you don't have, you should add property:
public int DeclatedById { get; set; }
Btw. this is very common problem and a lot of projects has duplicate values in db.
Maybe I should add that this will happen only if entity wasn't traced by EF context and was attached to it.

entity framework 6.1 - assign a forigen key cause to an insertion of new record

I seen similar posts but didn't find an answer. I have WPF 4.5 application with EF 6.1.
Here is my part of my data model:
[Key]
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
[Required]
[StringLength(32)]
public string FileDisplayName { get; set; }
[Required]
[StringLength(32)]
public string FileName { get; set; }
[Required]
[StringLength(8)]
public string FileExtention { get; set; }
[StringLength(1024)]
public string Description { get; set; }
[Required]
[StringLength(1024)]
public string FilePath { get; set; }
[Required]
public DateTime UploadDate { get; set; }
[Required]
public virtual FilesTypeLookup FileType { get; set; }
[Required]
[DefaultValue(0)]
public double Amount { get; set; }
[Required]
public virtual Expenses ExpenseId { get; set; }
public virtual ExpensesCategories Category { get; set; }
public virtual ExpensesPayees Payee { get; set; }
public class ExpensesCategories
{
[Key]
[Required]
public int Id { get; set; }
[Required]
[StringLength(64)]
[Index(IsUnique = true)]
public string Name { get; set; }
[StringLength(256)]
public string Description { get; set; }
}
As you can see, File entity has ExpensesCategory navigation property.
The problem happens when I'm assigning new value for this property.
I'm using the next code to editing existing File record:
var fileEntity = entityToEdit.Files.Single(p => p.Id == file.Id);
fileEntity.Amount = file.Amount;
fileEntity.Category = DB.ExpensesCategories.Single(p => p.Id == file.Category.Id);
//more work here
context.SaveChanges();
The SaveChanges() method is firing an exception:
System.Data.Entity.Infrastructure.DbUpdateException An error occurred while updating the entries. See the inner exception for details. Int32 SaveChanges()
UpdateException An error occurred while updating the entries. See the inner exception for details. Int32 Update()
SqlException Cannot insert duplicate key row in object 'dbo.ExpensesCategories' with unique index 'IX_Name'. The duplicate key value is (חומרי יצירה).
The statement has been terminated. Void OnError(System.Data.SqlClient.SqlException, Boolean, System.Action`1[System.Action])
It seems that instead of create a relationship between existing File record to existing ExpenseCategory, EF is trying to create a new ExpenseCategory record and link it with my existing File record. The unique constraint does not allows it and fires the exception.
I don't want that EF will create new ExpenseCategory records, just want to set relationships with existing records (ExpenseCategory is look-up table).
How can I do this?
Thanks
Ofir
Can you try this, add this to the ExpensesCategories class:
public virtual ICollection<Files> Files { get; set; }
Not sure if that will fix it but it's something that's missing anyway.
If there is one to one relationship between two objects
you should add the following properties to the ExpensesCategories
[Key, ForeignKey("File")]
public int FileId {get;set;}
public virtual File File{ get; set;}
In my opinion the relation ship between ExpensesCatrgories and Files is one to many (one category has may files but each file belongs to a specific category). In this case please add
public virtual ICollection<File> Files { get; set; }
to the ExpensesCategories

System.Data.SqlClient.SqlException: Invalid column name 'phone_types_phone_type_id'

I'm trying to get information from some of my models that have a foreign key relationships to my main employee model. If I map out each model individually, I can access them like normal with no problems, but I have to visit multiple different web pages to do so.
I'm trying to merge several of my models into essentially a single controller, and work with them this way. Unfortunately, when I try to access these models I get a strange error:
System.Data.SqlClient.SqlException: Invalid column name 'phone_types_phone_type_id'.
After searching through my code, apparently the only location phone_types_phone_type_id appears is in my migration code. I'm incredibly new at C# and Asp.Net in general so any help is appreciated.
Here is the code for my model:
[Table("employee.employees")]
public partial class employees1
{
public employees1()
{
employee_email_manager = new List<email_manager>();
employee_employment_history = new HashSet<employment_history>();
employee_job_manager = new HashSet<job_manager>();
employee_phone_manager = new HashSet<phone_manager>();
this.salaries = new HashSet<salary>();
}
[Key]
public int employee_id { get; set; }
[Display(Name="Employee ID")]
public int? assigned_id { get; set; }
[Display(Name="Web User ID")]
public int? all_id { get; set; }
[Required]
[StringLength(50)]
[Display(Name="First Name")]
public string first_name { get; set; }
[StringLength(50)]
[Display(Name="Last Name")]
public string last_name { get; set; }
[Column(TypeName = "date")]
[Display(Name="Birthday")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime birth_day { get; set; }
[Required]
[StringLength(1)]
[Display(Name="Gender")]
public string gender { get; set; }
[Required]
[StringLength(128)]
[Display(Name="Social")]
public string social { get; set; }
[Required]
[StringLength(128)]
[Display(Name="Address")]
public string address_line_1 { get; set; }
[StringLength(50)]
[Display(Name="Suite/Apt#")]
public string address_line_2 { get; set; }
[Required]
[StringLength(40)]
[Display(Name="City")]
public string city { get; set; }
[Required]
[StringLength(20)]
[Display(Name="State")]
public string state { get; set; }
[Required]
[StringLength(11)]
[Display(Name="Zip")]
public string zip { get; set; }
[Column(TypeName = "date")]
[Display(Name="Hire Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime hire_date { get; set; }
[Column(TypeName = "date")]
[Display(Name="Separation Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime? termination_date { get; set; }
[StringLength(70)]
[Display(Name="Emergency Contact Name")]
public string emergency_contact_name { get; set; }
[StringLength(15)]
[Display(Name = "Emergency Contact Number")]
public string emergency_contact_phone { get; set; }
[Display(Name = "Notes")]
public string notes { get; set; }
public virtual ICollection<phone_manager> employee_phone_manager { get; set; }
[Table("employee.phone_manager")]
public partial class phone_manager
{
[Key]
public int phone_id { get; set; }
public int employee_id { get; set; }
[Required]
[StringLength(15)]
public string phone_number { get; set; }
[StringLength(5)]
public string phone_extension { get; set; }
public int phone_type { get; set; }
[Column(TypeName = "date")]
public DateTime date_added { get; set; }
public bool deleted { get; set; }
public virtual employees1 employees1 { get; set; }
public virtual phone_types phone_types { get; set; }
}
[Table("employee.phone_types")]
public partial class phone_types
{
public phone_types()
{
phone_manager = new HashSet<phone_manager>();
}
[Key]
public int phone_type_id { get; set; }
[Required]
[StringLength(50)]
public string phone_type_name { get; set; }
public virtual ICollection<phone_manager> phone_manager { get; set; }
}
}
And the pertinent code from my view:
#foreach (var item in Model.employee_phone_manager)
{
#Html.DisplayFor(modelItem => item.phone_number);
#: -
#Html.DisplayFor(modelItem => item.phone_type);
<br />
}
EDIT I may have found out the issue, but I'll definitely take more input if there is another option. My solution was to take and add the following: [ForeignKey("phone_type")] directly above this line: public virtual phone_types phone_types { get; set; } in my phone_manager class.
Your issue is that your connection string in data layer and connection string in web layer are pointing to different databases.
e.g.
data layer reading dev database
webapp pointing to test database.
Either update connection strings to point to the same database.
or
Make sure your both database have same tables and columns.
After doing quite a bit more research, it seems like I had a fairly unique issue. I attempted several of the fixes listed both on here and many other sites, but almost nothing seemed to fix the issue.
However, the solution I listed at the bottom of my original post seems to be working, and holding up well, so I believe it to be a fairly adequate solution to my problem.
To somewhat outline what was occurring, MVC EF was attempting to find a fk/pk relationship across two models, but since the column names across the models were different, it wasn't able to map them properly. If I were to trying to get all the emails from email_manager by using the email_types table, it wasn't an issue, but moving backwards, and grabbing the information from email_types from email_manager threw errors.
Since the column names between the two tables are different, EF tried to create a column to house the relationship, but since no such column existed, an error was thrown. To correct this, all that's necessary is to tell EF what the foreign key column actually is, and that is done by using [ForeignKey("email_type")] above the collection that houses the parent model.
So for example, my new email_types and email_manager models were as follows:
[Table("employee.email_manager")]
public partial class email_manager
{
[Key]
public int email_id { get; set; }
public int employee_id { get; set; }
[Required]
[StringLength(255)]
public string email { get; set; }
public int email_type { get; set; }
[Column(TypeName = "date")]
public DateTime date_added { get; set; }
public bool deleted { get; set; }
[ForeignKey("email_type")]
public virtual email_types email_types { get; set; }
public virtual employees1 employees1 { get; set; }
}
[Table("employee.email_types")]
public partial class email_types
{
public email_types()
{
email_manager = new HashSet<email_manager>();
}
[Key]
public int email_type_id { get; set; }
[Required]
[StringLength(50)]
public string email_type_name { get; set; }
public virtual ICollection<email_manager> email_manager { get; set; }
}
I had the similar issue. What happens is that in the database foreign keys are created and it starts mapping both the models and then throws an exception. Best way is to avoid foreign key creation by using [NotMapped] as you could use complex models and also avoid creation of Foreign Key.
You have specify the Database Table using [Table("employee.employees")]. Check your database Table is there have a column that name is phone_types_phone_type_id .It Try to find data of that column but It did not find column then throw this Message. My Problem has solve Check my database database Table.
I'm using nop commerce and to get around my problem I had to use ignore in my database map
Ignore(p => p.CategoryAttachmentType);
In the domain I had
/// <summary>
/// Gets or sets the category attachment type
/// </summary>
public CategoryAttachmentType CategoryAttachmentType
{
get
{
return (CategoryAttachmentType)this.CategoryAttachmentTypeId;
}
set
{
this.CategoryAttachmentTypeId = (int)value;
}
}
I came across the same kind of exception. My solution is to go to the model class and verify the exception given property definition/type where it defines. In here better check the Model class/classes where you define 'phone_types_phone_type_id'.
You are right.
I had similar issue.
Something like this
[ForeignKey("StatesTbl")]
public int? State { get; set; }
public StatesTbl StateTbl { get; set; }
So as you can see, I had kept name 'StateTbl' in the last line instead of 'StatesTbl'
and app kept looking for StateTblID. Then I had to change name to 'StatesTbl' instead. And then it started working well.
So now, my changed lines were:
[ForeignKey("StatesTbl")] <== 'StatesTbl' is my original States table
public int? State { get; set; }
public StatesTbl StatesTbl { get; set; }
These are in the AppDbContext.cs class file
I had an issue where I was getting the same error and I resolved it by deleting the audit trail I had created and creating a new one. I had forgotten to do this when I deleted some columns from the table earlier on.
My problem is that I forgot that I've created several SQL Views in my database.
I've used those views in my ASP.NET C# MVC app.
So when I received error I naturally checked all databases tables but forgot about views in which I didn't add new fields.

Categories