System.DateTime couses error while migration - asp.net-mvc

I got the following class in my models
public DateTime DateTimePosted { get; set; }
and it's causing this error while DB migrations
"Cannot insert the value NULL into column 'DateTimePosted"
but when I allow nulls in my model this way
public DateTime? DateTimePosted { get; set; }
then migration is succesfull , but column in Db stays nullable,
but when I'm trying to pass it to Db by Seed method it works fine.
This is my controller
public ActionResult AddApartment()
{
return View(new Apartment { DateTimePosted = DateTime.Now });
}
My question is
How to pass to DB date and time of posted data

You get this error because you are trying to add new non-nullable column on a table that already contains some data. Because you're adding a non-nullable column, DB Migrations doesn't know which value to set for the new column to thos already inserted lines into your table. To fix that you have two solutions:
Making DateTimePosted a nullable data by using DateTime?
Modify your newly generated migration file by locating the line that add your new column and add set the defaultValueSql parameter like below :
The code:
AddColumn("YOUR_TABLE_NAME", "DateTimePosted",
c => c.DateTime(nullable: false, defaultValueSql: "GETUTCDATE()")
);

Related

Set a Primary Key for an Entity without ingaffect database

I'm working on an ASP.NET MVC project, I use Entity Framework (Database First), I created a data model depend on SQL server database, I created a Table in the database and I updated the data model from the database, and when I try to add a record to the new table I created (this table doesn't have a PK) I got an error, when I search about the error I Understood that in Entity Framework need to have a PK for Entity.
So I ASK if I can set a Primary Key for an Entity without affect database, or any other solution to solve this problem.
You can use partial Class for set Key and without effect Original Model and Database
// orginal class **Entity** `YourEntity.cs`
public class YourEntity
{
public int Id { get; set; }
}
Then create a new Class must name different ordinal class ex YourEntityMeta.cs it is physical name
// must change name ordinal class `YourEntity.cs` but add **partial** keyword
[MetadataType(typeof(Metadata))]
public partial class YourEntity
{
sealed class Metadata
{
[Key]
public int Id { get; set; }
}
}
Entity Framework always needs a primary key column with name id. Add a column (id) in the database table and set "Is Identity: true" for it. Then update the database model of your project.

Getting a the new value of RowVersion using Entity Framework 6

Is is possible, to get the new value of RowVersion using the same DbContext, without reloading the entity from the database?
Scenario:
Load data into editor form
Save new values
The row in the table gets updated, new value of RowVersion is generated
However, the saved entity still holds the old value of RowVersion, so the new value can not be passed back to the client
All concurrency control articles are usually concerned only with preventing the update (e.g. see this).
However, in the example from the article, a successful update is followed by a redirect to page, where the saved entity is read again and now it has a new RowVersion value. I would like to avoid this redirect.
Thanks to grennis, I found out the source of my problems.
I defined the interface and an entity like
public interface IRowVersion
{
// Attention: this will not be "inherited" by the implementing class !!!
[Timestamp]
byte[] VersionStamp { get; set; }
}
public class Directory : IRowVersion
{
[Key]
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
// If this attribute is missing here, then row version is used
// My initial version was without this attribute
[Timestamp]
public byte[] VersionStamp { get; set; }
}
In my problematic version, I thought that having the attribute on the interface property is enough. However, the attribute must be explicitly applied on the entity's property. Otherwise it will not be used at all (not even as the part of update SQL statement). The value was updated only because the DB updates the column value automatically and of course, at next read, I got the new value.
Not entirely related to the problem, but still worth mentioning... The following is really a killer feature of EF6
ctx.Database.Log = s => Debug.Write(s);
SQL Profiler, it was nice knowing you :-)

Insert values to entity framework in asp.net mvc4

In my asp.net mvc4 sample i have table in the name of Sample with three column as Name,Dept and Id.In this Id as identity and primary.I get a value for Name and Dept from user and insert that value to Sample table of entity framework.It pass value '0' to Id.And i got an error as "Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries".Please help me.
set "autoincrement" on the column and set the id as primary key in sql server ..
In EF code-first this is done by data annotations. Make sure you recreate your table (or database) after changing the scheme.
public class Sample
{
[Key]
[Required]
[Column(Order = 0)]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)] //auto increment id
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public int Dept { get; set; }
}
You don't need to pass an integer for Id. EF will resolve this automatically. Just create the object by filling in the name and the dept. By saving the changes to the database, EF will automatically fill in the auto generated Id.

Concurrency/Timestamp required for new Entity

Trying to save a new Entity with this field
[Timestamp]
public byte[] TimeStamp { get; set; }
throws the validation error Required. I am not setting any value on TimeStamp before save. Saving an existing item changes the TimeStamp in the DB as expected.
This value is set by the DB itself and as such does not need to be initialized, or am I wrong here?
EDIT:
This works i think because it is nullable
[ConcurrencyCheck]
public int? RowVersion { get; set; }
A new DB-Entry has null as value. Any change from within my app changes this and adds 1.
This was a bug and is now fixed in v 0.76.4. You should be able to use SQL Server timestamps cleanly now. ... Thanks for finding this, Sascha.

EF code first - change generated column name for relationship

Using EF code first want to control the name of the genereted column WHEN REFERENCING SELF. Tried [ForeignKey] and [Column] attributes. [Column] does not work and [ForeignKey] forces a relationship that seems to cause a problem. I have used [ForeignKey] attribute to set the name of a column in another class/table connected to this one.
Have
public class Episodes
{
public long ID {get; set;}
// ... other properties
public List<Episodes> Children { get; set; }
}
want a table (ID, ..., ParentID) - get a table (ID, ..., Episode_ID)
If you don't have the foreign key column exposed as property in your entity class you can define the column name only with Fluent API:
modelBuilder.Entity<Episodes>()
.HasMany(e => e.Children)
.WithOptional()
.Map(m => m.MapKey("ParentID"));
I assume that the parent is optional (ParentID is a nullable column in the DB table) because, I guess, there should be some "root" in the tree, i.e. an episode that doesn't have a parent anymore, hence at least for this episode the ParentID column must be NULL.

Resources