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(),
Related
Suppose I have a .NET Entity Framework model class:
public class Foo
{
public int FooId { get; set; }
public string Description { get; set; }
public DateTime Created { get; set; }
public DateTime LastUpdated { get; set; }
}
The Created and LastUpdated columns in my SQL Server table, both of type DATETIME2, have a DEFAULT constraint (SYSUTCDATETIME()). An AFTER UPDATE trigger sets LastUpdated to SYSUTCDATETIME whenever the Description is changed.
In my code, when I'm reading from the Foo table, I want Created and LastUpdated included, because I want to use their values. But when I'm adding a row to the table, I don't want them included in the Add because I want SQL Server to use the default value I've configured it to use. I thought it would just have been a matter of having
Foo foo = new Foo
{
Description = "This is my latest foo."
}
but C# is giving the two date properties their own default value of 0001-01-01T00:00:00.000000, which isn't null, and this is what's getting recorded in the table.
Isn't there an attribute that tells the framework not to write a property back to the database? It isn't NotMapped because that would prevent the values from being read.
`Don't you hate when you find the answer right after posting your question?
[DatabaseGenerated(DatabaseGeneratedOption.Computed)] omits the property from inserts and updates.
[DatabaseGenerated(DatabaseGeneratedOption.Identity)] omits the property from inserts.
The latter will take care of EndDate, which I didn't illustrate in my post. I have the database set a default value of 9999-12-31T23:59:59 on insert, but my application will change its value later when Foo is meant to expire.
What kills me is they based the naming on specific use cases that wouldn't come to mind in a different scenario. They ought to have gone with [SkipOnInsert] and [SkipOnUpdate] (which could then be combined as needed).
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()
If I have a model class
public class Foo
{
public string Property1 { get; set; } = string.Empty;
... other properties omitted for brevity
}
It gets save to the database as null since it is not a required property. But now when I retrieve the entity that property is null.
I have a lot of not required string properties on this entity and I don't want to have to do a lot of null checking on those properties, I just want them to be rehydrated as empty strings if they are null in the database. I don't mind them being stored in the db as null but when the entity is retrieved from the db I would like to have it mapped back to empty string if it is null in the db.
I'm thinking this must be a fairly common scenario and was wondering if I'm missing some simple way to do it with a configuration setting or something. I am fairly new to using EF.
In my OnModelCreating for this property I have:
.HasMaxLength(50)
.HasDefaultValue(string.Empty)
but it still gets stored as null and rehydrated as null. Again I don't mind it being stored as null but I want it hydrated as empty string if it is null in the db.
I tried modifying the model class like this:
private string property1 = string.empty;
public string Property1
{
get { return property1; }
set { property1 = value ?? string.Empty; }
}
thinking that EF must have to use the setter but this still resulted in a null property. So far the only way I've been able to solve it by making the property like this:
private string property1 = string.empty;
public string Property1
{
get { return property1 ?? string.empty; }
set { property1 = value ?? string.Empty; }
}
I'd really rather not have to make all my properties like that.
Can anyone suggest a cleaner way to do this or correct me if I'm doing something wrong or unusual or thinking about it wrong. Am I missing some easier way to achieve this?
I don't want to make the property required since empty string would not satisfy that case either.
The question's original Entity Framework version was EF7, the first ef-core version that was renamed to EF-core 1 later. The described behavior considerably differs from the current EF-core version (2.1.1).
Let me mention the two key points:
1
It gets save to the database as null since it is not a required property. But now when I retrieve the entity that property is null.
That's not what happens currently.
Take a simple class:
public class Item
{
public int ID { get; set; }
public string Name { get; set; }
public string Code { get; set; } = string.Empty;
}
When adding an Item of which only Name is set, the following SQL is executed:
exec sp_executesql N'SET NOCOUNT ON;
INSERT INTO [Items] ([Code], [Name])
VALUES (#p0, #p1);
SELECT [ID]
FROM [Items]
WHERE ##ROWCOUNT = 1 AND [ID] = scope_identity();
',N'#p0 nvarchar(4000),#p1 nvarchar(50)',#p0=N'',#p1=N'Item1'
The empty string is part of the insert statement. Also, when retrieving the item from the database, its Code is an empty string.
2
In my OnModelCreating for this property I have:
.HasMaxLength(50)
.HasDefaultValue(string.Empty)
but it still gets stored as null and rehydrated as null.
That, too, is different now. Take the same class but now with:
public string Code { get; set; } // removed "= string.Empty;"
...and mapping for Code:
modelBuilder.Entity<Item>().Property(p => p.Code).HasMaxLength(50).HasDefaultValue(string.Empty);
...then this is the resulting table:
CREATE TABLE [Items] (
[ID] int NOT NULL IDENTITY,
[Name] nvarchar(50) NOT NULL,
[Code] nvarchar(50) NULL DEFAULT N'', -- Default constraint
CONSTRAINT [PK_Items] PRIMARY KEY ([ID])
);
As you see, the mapping instruction is translated into a database default.
When adding an Item of which only Name is set, the following SQL is executed:
exec sp_executesql N'SET NOCOUNT ON;
INSERT INTO [Items] ([Name])
VALUES (#p0);
SELECT [ID], [Code]
FROM [Items]
WHERE ##ROWCOUNT = 1 AND [ID] = scope_identity();
',N'#p0 nvarchar(50)',#p0=N'Item1'
So EF inserts the item and reads back the generated default value in order to keep the tracked entity in sync with the database. Likewise, an item read from the database later has an empty string in Code.
These findings confirm that EF7 was a very immature version of EF-core (although I didn't confirm that it really displayed the described behavior). There have been more, and more profound, breaking changes since it. I hope we will soon forget about these early EF-core versions. Since version 2.0, EF-core is finally developing into a production-ready ORM.
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/
Actually i have manually entered records in mysql database-using grails but i want to show the date in a coloumn in same table.
Is there any solution for this
here is my controller class
class test {
String company_name
String contact_person
Integer phone_no
String status
String place
String address
static constraints = {
company_name(nullable:false)
contact_person(nullable:false)
phone_no(uinque:true,nullable:false)
status(nullable:false)
place(nullable:false)
address( nullable:false )
}
}
Grails provides automatic timestamps via the "dateCreated" property:
Automatic timestamping
If you define a dateCreated property it will be set to the current
date for you when you create new instances. Likewise, if you define a
lastUpdated property it will be automatically be updated for you
when you change persistent instances.
(From the Grails user guide: Events and auto timestamping)
Have a look at dateCreated and lastUpdated in autoTimestamp property in GORM.