I have an issue during an insert operation into the table using Entity Framework Core.
_context.Entry(item).State = EntityState.Added;
var r = await _context.ServiceWorkOrders.AddAsync(item);
_context.SaveChangesAsync(); <-- (fails)
Some context when dealing with this issue.
The table is owned by client so I have to work around this issue
The table to insert into, contains triggers and stored procedures set to run after Insert/Update/Delete operations.
The table have relationship properties (Foreign keys)
The table's primary key is set to auto-increment, hence the primary key field of the inserting entity is set to 0, along with the fields that is required during this insert.
I am trying to use Stored Procedure directly using ExecuteSqlCommand, but I would prefer to use EF to manage the database access. Moreover, correct me if I am wrong, I would have to list all the optional parameters in the Stored Procedure in order to add the entity in to prevent writing into the wrong fields. Currently this method inserts the entity, but it writes on the wrong fields, even if I used SqlParameters("#named_field", value).
I have tried using the Synchronous method as well, but it gives the same exception.
The exception returned:
Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: 'Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding and handling optimistic concurrency exceptions.'
edit:
Here is the entity model:
[Table("ASM_ServiceWorkOrder")]
public class ServiceWorkOrder: BaseEntity
{
[Key, Column(name: "ROWUID"), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int RowUID { get; set; }
[Column(TypeName = "nvarchar(25)")]
public string CompanyID { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string DocNumber { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string RevisionNumber { get; set; }
[Column(TypeName = "nvarchar(40)")]
public string CustomerDirectoryID { get; set; }
[ForeignKey("CustomerLocation")]
public Int32? CustomerLocationRowUID { get; set; }
public AssetLocation CustomerLocation { get; set; }
[Column(TypeName = "nvarchar(50)")]
public string WorkOrderType { get; set; }
[Column(TypeName = "nvarchar(25)")]
public string IssueType { get; set; }
[Column(TypeName = "nvarchar(40)")]
public string AssetItemCode { get; set; }
[Column(TypeName = "nvarchar(40)")]
public string AssetSerialNo { get; set; }
[ForeignKey("AssetRegister")]
public int? AssetRegisterROWUID { get; set; }
public AssetRegister AssetRegister { get; set; }
[Column(TypeName = "nvarchar(40)")]
public string ProjectDirectoryID { get; set; }
[Column(TypeName = "nvarchar(10)")]
public string Priority { get; set; }
[Column(TypeName = "nvarchar(25)")]
public string Status { get; set; }
[Column(TypeName = "nvarchar(25)")]
public string StatusForClient { get; set; }
public bool? Billable { get; set; }
[Column(TypeName = "decimal(18, 2)")]
public decimal? QuotedFee { get; set; }
[Column(TypeName = "datetime")]
public DateTime? DueDate { get; set; }
[Column(TypeName = "nvarchar(240)")]
public string Description { get; set; }
[Column(TypeName = "nvarchar(50)")]
public string ReportedBy { get; set; }
[Column(TypeName = "datetime")]
public DateTime? ReportedDate { get; set; }
[Column(TypeName = "nvarchar(35)")]
public string BusinessDataType { get; set; }
[Column(TypeName = "nvarchar(240)")]
public string DocRemarks { get; set; }
[Column(TypeName = "nvarchar(2000)")]
public string ErrorText { get; set; }
public Guid? RowGlobalUID { get; set; }
public Int32? HeaderROWUID { get; set; }
[Column(TypeName = "datetime"), DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime? DateOfDocument { get; set; }
//[Timestamp]
//public byte RowVersion { get; set; }
//public IList<ServiceWorkOrderAttachment> Attachments { get; set; }
public IList<ServiceWorkOrderDetails> Details { get; set; }
}
Are u sure u created ITEM? And indicate table where u try save row?
If u wanna insert row in table u must create your item first.
f.ex:
var = new ServiceWorkOrders(){Column1=var1,Column2=var2 etc.};
await _context.ServiceWorkOrders.AddAsync<ServiceWorkOrders>(item);
await _context.SaveChangesAsync();
Related
I'm using EF Core and my context is configured with SQL Server. When I to call context.SaveChangesAsync I get the following error message:
Failed executing DbCommand (3,643ms) [Parameters=[#p0='?' (Size = 4000), #p1='?' (DbType = Int32), #p2='?' (Size = 4000), #p3='?' (Size = 4000), #p4='?' (DbType = DateTime2), ...
And the inner exception is:
Operand type clash: datetime2 is incompatible with text
Does anyone know what this means?
For context, this is my DbContext:
public class ComparisonInfoContext : DbContext
{
public DbSet<ComparisonInfo> Comparisons { get; set; } = null!;
public ComparisonInfoContext(DbContextOptions<ComparisonInfoContext> options)
: base(options)
{
}
}
And this is ComparisonInfo (the entity it the DbSet).
public class ComparisonInfo
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string User { get; set; }
public DateTime InitiatedDateTime { get; set; }
public string TaskName { get; set; }
public string Job { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public string Client { get; set; }
public string Version1 { get; set; }
public string Version2 { get; set; }
public string ControlDb1 { get; set; }
public string ControlDb2 { get; set; }
public string Org { get; set; }
public JobStatus VersionStatus1 { get; set; }
public JobStatus VersionStatus2 { get; set; }
public ComparisonResult ComparisonResult { get; set; }
public List<DiscrepancyInfo> DiscrepancyInfos { get; set; } = new List<DiscrepancyInfo>();
public bool HasBeenPassedToComparePay { get; set; } = false;
}
And lastly here is DiscrepancyInfo (ComparisonInfo stores a list of this):
public class DiscrepancyInfo
{
public int Id { get; set; }
public int? EmployeeId { get; set; }
public DateTime date { get; set; }
//this is an enum
public DiscrepancyPattern DiscrepancyPattern { get; set; }
}
At the moment I am trying to save, the DbSet contains only a single instance of ComparisonInfo and the instance's list of DiscrepancyInfo's is empty.
The issue was happening because I was previously using SqlLite instead of SqlServer. All the migrations were made for SqlLite and deleting them fixed the issue.
When I do an insert using EF6, I get this error
The column name 'employee_id' is specified more than once in the SET clause. A column cannot be assigned more than one value in the same SET clause. Modify the SET clause to make sure that a column is updated only once. If the SET clause updates columns of a view, then the column name 'employee_id' may appear twice in the view definition
My models looked like this:
public class Entity
{
public Entity()
{
IsActive = true;
IsDeleted = false;
DateCreated = DateTime.Now;
}
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long ID { get; set; }
public int CompanyID { get; set; }
public int SubID { get; set; }
public DateTime DateCreated { get; set; }
public bool IsTransient()
{
return EqualityComparer<long>.Default.Equals(ID, default(long));
}
public bool IsDeleted { get; set; }
public bool IsActive { get; set; }
}
public partial class NextOfKin : Entity
{
[Required]
public long employee_id { get; set; }
[StringLength(100)]
[Required]
public string nok_first_name { get; set; }
[StringLength(100)]
[Required]
public string nok_last_name { get; set; }
[StringLength(300)]
[Required]
public string nok_address { get; set; }
[StringLength(100)]
public string nok_email { get; set; }
[StringLength(100)]
public string nok_phone { get; set; }
[StringLength(100)]
public string nok_employer { get; set; }
[StringLength(300)]
public string nok_work_address { get; set; }
[StringLength(100)]
[Required]
public string nok_relationship { get; set; }
public virtual Employee Employee { get; set; }
}
public class Employee : Entity
{
//Person Records
public long UserId { get; set; }
public int TitleId { get; set; }
public int? ReligionId { get; set; }
public string SerialNo { get; set; }
[StringLength(100)]
[Required]
public string FirstName { get; set; }
[StringLength(100)]
[Required]
public string LastName { get; set; }
}
My insert code into next of kin was like this.
NextOfKin nextOfKin = new NextOfKin();
nextOfKin.employee_id = newEmployee.ID;
nextOfKin.nok_first_name = "Friday";
nextOfKin.nok_last_name = "Ben";
nextOfKin.nok_address = "XXX";
nextOfKin.nok_email = "xa#xo.com";
nextOfKin.nok_phone = "023938494";
nextOfKin.nok_employer = "50 Queens Street";
nextOfKin.nok_work_address = "51 Queens Street";
nextOfKin.nok_relationship = "Neighbour";
db.NextOfKins.Add(nextOfKin);
db.SaveChanges();
I got an error like this using EF Core
'PropertyNameID' is specified more than once in the SET clause or
column list of an INSERT. A column cannot be assigned more than one
value in the same clause. Modify the clause to make sure that a column
is updated only once. If this statement updates or inserts columns
into a view, column aliasing can conceal the duplication in your code.
It turned out that I had the case wrong in my relatonship
In My business object I had the foreign key set with the wrong case.
public int PropertyNameID { get; set; }
[ForeignKey("PropertyNameId")] public virtual PropertyNameExt PropertyName { get; set; }
Should have been
[ForeignKey("PropertyNameID")] public virtual PropertyNameExt PropertyName { get; set; }
To fix this, remove the relationship on next of kin model, then do migration.
To remove, remove public virtual Employee Employee { get; set; } from NextOfKin model.
The reason for this issue is as follow:
Relationships are only created properly if you name the reference property properly. In this case you should use EmployeeID instead of employee_id for the relationship between next of kin and employee.
The Employee model does not have a link back to the next of kin model. If it's a one to many you can add the property below to the Employee model.
public virtual List NextOfKins{get; set;} //if you need lazy loading
or
public List NextOfKins{get; set;} //if you don't need lazy loading
I've similar questions that refer to this annotation to solve their problem:
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
However, applying this to my relevant Entity Model does nothing.
When I call the .Add() method, it inserts the GUID as 00000000-0000-0000-0000-000000000000.
As you can see, the annotation I mentioned is present in the model:
using System;
using System.Collections.Generic;
public partial class Event
{
[System.ComponentModel.DataAnnotations.Schema.DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
public System.Guid ID { get; set; }
public int AccountID { get; set; }
public string ExternalID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Location { get; set; }
public Nullable<System.DateTime> StartTime { get; set; }
public Nullable<System.DateTime> EndTime { get; set; }
public Nullable<bool> AllDay { get; set; }
public Nullable<System.Guid> ImageData { get; set; }
public string ImageUrl { get; set; }
public virtual Account Account { get; set; }
public virtual FetchedFile FetchedFile { get; set; }
}
How can I generate a unique GUID upon inserting a new Entity Object?
You can always initialize the Guid in a constructor.
public partial class Event
{
public Event()
{
ID = Guid.NewGuid();
}
public System.Guid ID { get; set; }
public int AccountID { get; set; }
public string ExternalID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Location { get; set; }
public Nullable<System.DateTime> StartTime { get; set; }
public Nullable<System.DateTime> EndTime { get; set; }
public Nullable<bool> AllDay { get; set; }
public Nullable<System.Guid> ImageData { get; set; }
public string ImageUrl { get; set; }
public virtual Account Account { get; set; }
public virtual FetchedFile FetchedFile { get; set; }
}
First I'll show you what I do, and that there is. My project in ASP.NET MVC 3.
This is model for table Business.
[Table("Business")]
public class Business
{
[Key]
public long? BusinessId { get; set; }
public Int32 LegalTypeId { get; set; }
public Int16 BusinessTypeId { get; set; }
public Int64 OwnerId { get; set; }
public Int32 MainIndustryFieldId { get; set; }
public String NameNative { get; set; }
public String NameEnglish { get; set; }
public Byte[] Logo { get; set; }
public DateTime CreateDate { get; set; }
public virtual User Owner { get; set; }//It is Forign key with user table
}
[Table("User")]
public class User
{
[Key]
public Int64 UserId { get; set; }
public String UserName { get; set; }
public String LoweredUserName { get; set; }
public String FirstName { get; set; }
public String LastName { get; set; }
public String Email { get; set; }
public String LoweredEmail { get; set; }
public String Password { get; set; }
public String PasswordSalt { get; set; }
public String PasswordQuestion { get; set; }
public String PasswordAnswer { get; set; }
public Boolean IsApproved { get; set; }
public Boolean IsLocked { get; set; }
public DateTime LastActivityDate { get; set; }
public DateTime LastLoginDate { get; set; }
public DateTime CreateDate { get; set; }
public virtual Business Bussines { get; set; }
}
when I want to add information:
user.Business = new Business
{
OwnerId = user.UserId,
LegalTypeId = business.LegalTypeId,
BusinessTypeId = business.BusinessTypeId,
MainIndustryFieldId = business.MainIndustryFieldId,
NameNative = business.NameNative,
NameEnglish = business.NameEnglish,
Logo = business.Logo,
CreateDate = DateTime.Now
};
ctx.SaveChanges();
I get the following error:
Cannot insert explicit value for identity column in table 'Business'
when IDENTITY_INSERT is set to OFF.
In database column identity specification business chose is Identity Yes.
Somebody can tell what to do.
Can you make sure that in your EDMX model, your BusinessId is set to be handled by the database (property StoreGeneratedPattern = Identity)?? Also: why is your primary key nullable (long?) - makes no sense whatsoever. Your primary key must never be null !
BusinessId can not be empty/null since you have not specified that it should be autogenerated by Sql Server (which Identity means).
Since you are using Code First to generate your database, just change to:
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long? BusinessId { get; set; }
override OnModelCreating in DbContext and add in it following Fluent API:
modelBuilder.Entity<Business>().HasRequired(m => m.Address).WithRequiredPrincipal(m => m.Business).WillCascadeOnDelete(true);
I want to update a table row and I have a following Code
void updatePrimaryPaymentAndSecondaryPaymentSourceTypes()
{
LookUpDetails lookUpDetail = new LookUpDetails();
var repo = new SimpleRepository("E2Lending", SimpleRepositoryOptions.RunMigrations);
lookUpDetail = repo.Single(80);
lookUpDetail.Col1Value = "My Checking Account";
repo.Update(lookUpDetail);
}
public class LookUpDetails
{
[SubSonicPrimaryKey]
public int LookUpDetailId {get; set;}
public int LookUpGroupId { get; set; }
public string Code { get; set; }
public int SortOrder { get; set; }
public string Col1Value { get; set; }
[SubSonicNullString]
public string Col2Value { get; set; }
[SubSonicNullString]
public string Col3Value { get; set; }
[SubSonicNullString]
public string Col4Value { get; set; }
[SubSonicNullString]
public string Col5Value { get; set; }
public DateTime CreatedOn { get; set; }
public string CreatedBy { get; set; }
public DateTime ModifiedOn { get; set; }
public string ModifiedBy { get; set; }
public Boolean IsActive { get; set; }
}
When I execute then repo.Update(lookUpDetail); shows me Null reference Exception.
Can you please tell me How I will be able to update a single record in a table?
Regards
I have the very same problem with very simple model class:
class Person
{
public long ID {get;set;}
public string Name { get; set;}
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection collection) {
Person toUpdate = Repository.All<Person>().Single(p => p.ID == id);
TryUpdateModel(toUpdate, collection.ToValueProvider());
Repository.Update(toUpdate); //throws nullreferenceexception
return RedirectToAction("Index");
}
stack trace:
at SubSonic.Query.Update.GetCommand()
at SubSonic.Query.Update.Execute()
at SubSonic.Repository.SimpleRepository.Update[T](T item)
at MvcApplication1.Controllers.PersonController.Edit(Int32 id, FormCollection collection)
in H:\...\Controllers\PersonController.cs:line 71"
My configuration: SubSonic 3, SQLite, empty database
I ran into this problem as well and I was able to download the latest SubSonic source and the issue was already fixed. Just open the SubSonic.Core project and do a build and replace your project's reference to SubSonic.Core.
Download Latest Source
http://github.com/subsonic/SubSonic-3.0
Boom - Repository Update works again!