Insert fails on Code First whith non-identity id key - asp.net-mvc

I have defined a model class with an ID column set as [Key], on an existing database table. the table has the field defined as primary key, int, not null. It is NOT and identity column.
When creating a new record in code, I am setting the ID column (to an unique value) in code before calling the SaveChanges() method.
The method returns with the error:
Cannot insert the value NULL into column 'xxx_id', table
'xxx.dbo.xxxxxx'; column does not allow nulls. INSERT fails. The
statement has been terminated.
It seems that EF assumes that the ID column is an Identity column and therefore doesn't pass the ID in the SQL call to the database.
Is there a way to define the ID column to tell EF that is it not an Identity column and to pass the value in the SQL call

You need to specify the DatabaseGeneratedOption for the property. In this case, the DatabaseGeneratedOption should be None.
See: http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.databasegeneratedoption%28v=vs.103%29.aspx
I have usually done this with fluent coniguration like:
Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
.. but it looks like this can also be specified with an attribute. See http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.databasegeneratedoption%28v=vs.103%29.aspx
[DatabaseGenerated(DatabaseGeneratedOption.None)]

Related

Change foreign key type without losing data.(asp.net)

I have created one to many relationship between student and department tables using entity framework.But unfortunately in the student table the foreign key (DepartmentId) type I gave string but it should be int.How can i resolve this issue without losing data????????
N.B: I am using entity framework code first approach.
I think you cannot do that, considering that your DepartamentID is the PK of the table Departament, so you have to drop the old field and create a new one, something like this
AddColumn("dbo.Departament", "DepartamentID2", c => c.Int(nullable: false));
Sql(#"
UPDATE dbp.Departament
SET DepartamentID2 = DepartamentID
");
Sql(#"
ALTER TABLE dbo.Departament drop CONSTRAINT <The FK Constraint>
");
DropColumn("dbo.Departament", "DepartamentID");
RenameColumn("dbo.Departament", "DepartamentID2", "DepartamentID");
Sql(#"
ALTER TABLE dbo.Departament add PRIMARY KEY (DepartamentID)
");
Sql(#"
ALTER TABLE dbo.Departament add CONSTRAINT <The FK
constraint>
");

Mapping a generated database column to a Grails domain class property

In my Grails 2.5.X app, I have a domain class that looks like this:
class FormData {
String submittedFields
Boolean submitted
static constraints = {
submittedFields nullable: true
}
static mapping = {
// can I do something here to map submitted to a generated
// column of the form_data table
}
}
I would like to map the submitted property to a generated column of the form_data table, i.e. a column that would be created by the SQL statement
alter table form_data add submitted tinyint
GENERATED ALWAYS AS (if(submitted_fields is null,0,1));
Specifically, this generated column should be created when I create the schema from the domain model, e.g. by running the schema-export script.
A consequence of submitted being mapped to a generated column is that the corresponding domain class property should be read-only, or at least, assigning a value to it should have no effect.
If you want to handle the value of the column on database side only, and dont want it to be inserted or updated from grails/hibernate side. you can make the column as insertable:false updatetable:false
static mapping = {
submitted insertable:false, updateable:false
}
Now, even if the value is changed in grails, the new value will not be updated in database.

C# mvc How to set AutoIncrement on

Hi I am trying to create a new customer record. The primary id customerid is autoincremental column.
When I try to insert a new record I get this error :
Message=Cannot insert explicit value for identity column in table 'Customer' when IDENTITY_INSERT is set to OFF.
This is the same code I am using :
NewCustomer.Name= user.Name;
NewCustomer.Address= user.Address;
NewCustomer.Phone = user.Phone;
NewCustomer.Email= user.Email;
db.Customers.Add(NewCustomer);
db.SaveChanges();
I read somewhere that I have to set autoincrement on, but I am using entity framework and not any direct sql.
Can some one please help how I could turn on autoincrement so I could insert records?

Websecurity.CreateUserAndAccount on Azure doesn't work

I have a method that registers a new user using WebSecurity.CreateUserAndAccount(model.UserName, model.Password) The problem is that in the UserProfile model I have added a GUID Key. On my local machine this just populates an empty Guid when I call this method. On azure however, I get the following error:
System.Data.SqlClient.SqlException (0x80131904): Cannot insert the value NULL into column 'Key', table 'Scheduler.dbo.UserProfile'; column does not allow nulls. INSERT fails.
Now, I've tried to generate a new GUID in the constructor of the model, manually have the Set{} generate a new GUID and I get the same error.
When I try to use the CreateUserAndAccount overload like:
WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { Key = Guid.NewGuid() });
I get the following syntax error (run time):
Incorrect syntax near the keyword 'Key'.
I've spent a good part of the morning trying to figure this out and I just can't. By the way all of the above methods still result in an empty GUID 00000000-0000-0000-0000-000000000000 and the overload gives me syntax error on my local machine.
"Key" is a reserved word in SQL, it should be used in brackets like this [Key]
Since you don't have control on how WebSecurity generate the SQL query then your only option is to rename it to something like UserKey

How to get primary key field name for null EntityReference?

I've made the following function to assign value to a foreign key reference (I know, it's dirty and does not work for compound keys):
void setFk(dynamic tbl,object id){
var path=db.DefaultContainerName+"."+tbl.TargetRoleName;
var ret=new System.Data.EntityKey(path, tbl.RelationshipSet.ElementType.RelationshipEndMembers[0].GetEntityType().KeyMembers[0].Name, id);
tbl.EntityKey=ret;
}
which I want to invoke by this: setFk(newRec.WorkItemsReference,src.WorkItemsId)
The problem is that it does not work for newly created object newRec because tbl.EntityKey and tbl.RelationshipSet are both null.
One route that I see is to get tbl.GetType() and somehow locate Id column from there. If this is the right route then how ?
Any other route ?
My goal was not to pass more arguments into setFk function because it's supposed to be sufficient with 2 arguments and would lead to duplication of entity name.

Resources