Cannot insert the value NULL into column 'EntryDate', table 'eApps.Logs.dbo.Logs'; column does not allow nulls. INSERT fails - entity-framework

I'm getting this error:
Cannot insert the value NULL into column 'EntryDate', table 'eApps.Logs.dbo.Logs'; column does not allow nulls. INSERT fails.
I have a standard add function to EF 6
public Logs AddLog(Logs p)
{
Logs.Add(p);
SaveChanges();
return p;
}
I've defined the field in my class as:
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime EntryDate { get; set; }
Should I be populating this field in my controller at all?

Please note that column EntryDate in table does not allow NULL. Hence, you must ensure that object p got valid date. Other option could be to change table schema and modify EntryDate column to accept NULL.

I added a constraint on the EntryDate field in SQL Server to default this field to GETDATE()

Related

EF Core - Change column type from varchar to uuid in PostgreSQL 13: column cannot be cast automatically to type uuid

Before:
public class MyEntity
{
public string Id { get; set; }
//...
}
Config:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//...
modelBuilder.Entity<MyEntity>()
.Property(e => e.Id)
.ValueGeneratedOnAdd();
}
This was the previous developer's code which resulted in GUID values for the column. But in C# I had to deal with strings, so I decided to change the model.
After:
public class MyEntity
{
public Guid Id { get; set; }
//...
}
And I removed the ValueGeneratedOnAdd() code from Fluent API config.
I get the column "Id" cannot be cast automatically to type uuid error.
I think the key in this message is the automatically word.
Now my question is that since the values on that column are already GUID/UUID, is there any way to tell Postgres to change the varchar type to uuid and cast the current string value to UUID and put it in the column? I'm guessing there should be a SQL script that can do this without any data loss.
Use USING _columnname::uuid. Here is an illustration.
-- Prepare a test case:
create table delme (x varchar);
insert into delme (x) values
('b575ec3a-2776-11eb-adc1-0242ac120002'),
('4d5c5440-2776-11eb-adc1-0242ac120002'),
('b575f25c-2776-11eb-adc1-0242ac120002');
-- Here is the conversion that you need:
ALTER TABLE delme ALTER COLUMN x TYPE uuid USING x::uuid;
In your particular case:
ALTER TABLE "MyEntity" ALTER COLUMN "Id" TYPE uuid USING "Id"::uuid;
Btw, is your application the sole owner of the database model? If not then changing an existing table is a bad idea.

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;

MVC + code first EF + Execute stored procedure and binding it to entity

I have a user entity as follows:
public int UserID { get; set; }
public DateTime? DOB { get; set; }
public string UserName { get; set; } and so on..
When I read the values using context to user entity everything works fine. But I have another table called tbl_transactions_User. Where I am using a trigger on tbl_user and inserting all the modified columns and their values. So let's say if I change my DOB value I am storing the prior data and updated data into the transaction table.
But the transaction table looks like:
[USER_KEY] [int] NULL,
[FIELD_NAME] [varchar](100) NULL,
[PRIOR_DATA] [varchar](255) NULL,
[UPDATED_DATA] [varchar](255) NULL
So when DOB column was modified in tbl_insured it will stored in tbl_transactions_User table. But as a varchar instead of actual datetime. So my user entity is expecting the DOB as datetime. But my stored procedure is returning values as varchar (I am using PIVOT and joins to get the modified column and its value from tbl_transactions_user and tbl_user tables)
So on my MVC front end it is returning error:
The 'DOB' property on 'UserEntity' could not be set to a 'String' value. You must set this property to a non-null value of type 'DateTime'.
Please help
thanks
Sounds like you need to convert your varchar type to datetime when you select it out in your stored procedure. How you do that depends on the format of the date when you are storing it as a string.
There are plenty of examples of conversion out there - here's one link: http://www.sqlusa.com/bestpractices/datetimeconversion/

EF Code First date field to equal current time

I have a field in my model class like below:
[ScaffoldColumn(false)]
public DateTime DatePosted { get; set; }
I would like that this field be set to DateTime.Now by default, unless a value was given. In MSSQL server this can be achieved in the table design view by setting the date field's property "Default Value or Binding" to getdate() - I think, please correct me if I'm wrong.
you can set default values in constructor of your model class,
public YourModel(){
this.DatePosted =DateTime.Now;
}
how can we add a DB contraint do do that.
some thing that will do the below SQL
[DateCreated] [datetime] NOT NULL DEFAULT GetDate(),

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

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.