I dont want to insert the PK val.But - Cannot insert explicit value for identity column in table 'Employees' when IDENTITY_INSERT is set to OFF - entity-framework

I am using the Entity Framework to update my database.
The Employee table has an employeeId primary key field.
When I instantiate an employee object, the employeeId defaults to zero.
I want to insert the employee object into the database, ignoring the primary key value of zero.
Yet I get this exception;
Cannot insert explicit value for identity column in table 'Employees' when IDENTITY_INSERT is set to OFF.
What should I be doing to stop this?
public void Add()
{
using (SHPContainerEntities db = new SHPContainerEntities())
{
// Set default values
this.StartDate = DateTime.Now;
// Start date now
this.SHP_UserRoleId = db.SHP_UserRoles.Where(x => x.RoleName == "Employee").Single().UserRoleId;
// Default user role is "Employee". This can be changed later.
this.DepartmentId = 1;
// This is a temporary fix.
db.AddToEmployees(this);
//db.Employees.AddObject(this);
db.SaveChanges();
}
}

I fixed the problem.
I updated the database and I forgot to update my edmx file to reflect that change.

Related

How can insert 00000000-0000-0000-0000-000000000000 with EF Core?

I want insert record on database by EF with Guid Id based on zero values (00000000-0000-0000-0000-000000000000). On my GetDefaultGuidUser() method I can generate this value with default(Guid) but when I want insert on database I receive exception.
Cannot insert the value NULL into column 'Id', table 'auth.Core.Users'; column does not allow nulls. UPDATE fails.
var user = new UserRepository().GetDefaultGuidUser();
_context.Users.Add(user);
_context.SaveChanges();
However, I can update database with SQL script like this:
UPDATE core.users SET Id = '00000000-0000-0000-0000-000000000000'
What's wrong?

IDENTITY_INSERT ON error with foreign key

I'm trying to set Id manually for some entries.
I have a Customer class with an Identity field
modelBuilder.Entity<Customer>().Property(f => f.Id).HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity);
and in the insert part I have
using (var transaction = ctx.Database.BeginTransaction())
{
ctx.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[Customers] ON");
ctx.Customers.AddRange(customersList);
ctx.SaveChanges();
ctx.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[Customers] OFF");
transaction.Commit();
}
but I'm still getting the exception
Explicit value must be specified for identity column in table
'Customers' either when IDENTITY_INSERT is set to ON or when a
replication user is inserting into a NOT FOR REPLICATION identity
column.
In the StateEntries of my exception, I can see that all the fields that are stored in another table like "Contacts" seems to be the cause
customer.Contacts = new List<Contact> {new Contact {Name = "Test", … }}
How can I make it work?
That error message is misleading. You are succeeding in turning IDENTITY_INSERT on, but EF is still generating an INSERT statement under the assumption that the key value will be generated by the IDENTITY column.
So you additionally must generate an INSERT statement containing the key value. You can, of course, use .ExecuteSqlCommand() to perform the INSERT as well. Or you can get EF to do it, but you must use a model where that Entity does not have database-generated keys. OnModelCreating configures the model only once per ModelType, so you can't just put a switch in there.
Instead you can create a subtype of your DbContext for seeding, overriding the entity configuration of the base DbContext. Like this:
class Db_Seed: Db
{
public Db_Seed(string constr) : base(constr)
{
Database.SetInitializer<Db_Seed>(null); //no initializer
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Customer>().Property(c => c.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
}
}
You still must set IDENTITY_INSERT on (since the table does have an IDENTITY), but with this context EF will not generate an INSERT statement that assumes the server will generate the key.

Selecting Postgres UUID's on Laravel

I have a table on Postgres that auto generates UUIDs, when I dd Customer::all(); on Laravel I get an array with "cs_id" => "d0402be5-e1ba-4cb2-a80c-5340b406e2c3" which is fine. When I loop or select one record with the only the cs_id the data it retuns 0,2,5 for the three records currently on the table which is incorrect data.
EDIT:
CREATE TABLE customers
(
cs_id character varying(255) NOT NULL DEFAULT gen_random_uuid(),
CONSTRAINT cs_customers_pkey PRIMARY KEY (cs_id),
}
On laravel
$customerData = Customer::where('cs_id','d0402be5-e1ba-4cb2-a80c-5340b406e2c3')->first();
dd($customerData['cs_id']);
For some reason Eloquent messes up there.
just add a getter and use it whenever you need the cs_id
public function getGuid()
{
return $this->attributes['cs_id'];
}
To use uuids auto-generated by the database, define your model as follows:
class Customer extends Model
{
// rename the id column (optional)
protected $primaryKey = 'cs_id';
// tell Eloquent that your id is not an integer
protected $keyType = 'string';
// do NOT set $incrementing to false
}
Then you can use all Eloquent's methods as you would with classic ids:
$customerData = Customer::findOrFail('d0402be5-e1ba-4cb2-a80c-5340b406e2c3');
Use Customer::findOrFail('d0402be5-e1ba-4cb2-a80c-5340b406e2c3');
to get the record matching that pk.
I'm assuming on top you have use App\Customer;

Adding column with foreign key into table.

I have some problem. I want to add new column into my table that references to other column in other table. I do something like that:
class m161202_153033_dodanie_informacji_o_obsludze_prawnej_do_pozyczki extends CDbMigration
{
public function safeUp()
{
$this->execute("ALTER TABLE loan ADD COLUMN administrator int NOT NULL DEFAULT 15 REFERENCES person (id) ON UPDATE CASCADE ON DELETE NO ACTION;");
}
public function safeDown()
{
$this->execute("ALTER TABLE loan DROP COLUMN administrator;");
}
}
But when i try to execute this migration i have this error:
Foreign key violation: 7
DETAIL: Key (administrator)=(15) doesn't appear in table "person"..
I know that there is no suck column "administrator" in my table. But i want to add new column "administrator" into loan table. I wanted to make "administrator" foreign key from person table, column "id". Can u help me, what am i doing wrong?
The error means that there is no row in person with id equal to 15, which would be required for the constraint to be fulfilled.
When you run that ALTER TABLE statement, the table has to be rewritten, and the new column is filled with the value 15.
Often it is easier to create a new column nullable and without default value (then ALTER TABLE will not rewrite the table) and use UPDATE to populate the new column. After that you can change the column definition to NOT NULL and add a default value.
Try this
class m161202_153033_dodanie_informacji_o_obsludze_prawnej_do_pozyczki extends CDbMigration
{
public function safeUp()
{
$this->execute("INSERT INTO person (id) VALUES (15) ON CONFLICT (id) DO NOTHING;");
$this->execute("ALTER TABLE loan ADD COLUMN administrator int NOT NULL DEFAULT 15 REFERENCES person (id) ON UPDATE CASCADE ON DELETE NO ACTION;");
}
public function safeDown()
{
$this->execute("ALTER TABLE loan DROP COLUMN administrator;");
}
}

Entity Framework Insert, Update, Delete During Same Transaction

I have a problem, I have a wizard that can update data AND insert data. So, if I have an existing list of team members, I can update their roles but If necessary, I can also add/insert a person to this team. So I can update roles and insert a new team member into the same table all during the same transaction. Data can be updated to and inserted to table teamMembers.
When I try to add a new teamMember, I also have an existing member where I simply want to update his role.
Both changes happen to the same table called TeamMember. When I debug the context, everything looks good. it shows that there are two changes that will occur for the TeamMember table. One transaction is the update and the other transaction is the insert. When I perform an update using:
var teamMember = new TeamMember
{
Name = user.FullName,
UserProfileId = user.UserProfileId,
RoleId = user.RoleId
};
TeamMemberList.Add(teamMember);
project.TeamMembers = TeamMemberList;
//And then call
this.Context.Projects.Attach(project);
this.Context.Entry(project).State = System.Data.EntityState.Modified;
it updates but the record that needs to be inserted fails.
HOW CAN I DO BOTH AN INSERT AND UPDATE TO THE SAME TABLE DURING THE SAME TRANSACTION?
CURRENT ERROR IS:
The changes to the database were committed successfully, but an error occurred while updating the object context. The ObjectContext might be in an inconsistent state. Inner exception message: A referential integrity constraint violation occurred: The property values that define the referential constraints are not consistent between principal and dependent objects in the relationship.
I think you need to add the TeamMember entity to the context's global list. Something like:
var teamMember = new TeamMember()
{
Name = user.FullName,
UserProfileId = user.UserProfileId,
RoleId = user.RoleId
}
project.TeamMembers.Add( teamMember );
this.Context.TeamMembers.Add( teamMember );
this.Context.SaveChanges();
How about loading the existing project entity first and then adding members.
var project = this.Context.Project.Where(p => p.ID = "bar").Include("TeamMembers").FirstOrDefault();
var teamMember= new TeamMember
{
Name = user.FullName,
UserProfileId = user.UserProfileId,
RoleId = user.RoleId
};
project.TeamMembers.Add(teamMember);
this.Context.SaveChanges()