Get Help:Ask a Question in our Forums|Report a Bug|More Help Resources
Last post Jan 07, 2013 12:45 AM by Decker Dong - MSFT
Jan 06, 2013 03:28 AM|LINK
What should be a simple task I am finding very difficult.
I want to insert a new row in the database. The row is represented as the object Product. The list of objects is returned with something like context.Products. So I am trying to add with the following code:
product.SKU = (currentSku++).ToString();
product.oid = currentOid++;
The above code throws an exception in Add indicating that oid is a key and cannot be modifed. If I remove this line then I get another exception because the oid is part of a primary key and the INSERT fails. So what do I do?
Jan 06, 2013 04:01 AM|LINK
The EF doesn't know that oid is the primary key. By convention it looks for a property named "ID" or class name plus "ID".
So you have to use the afluent API to configure. First ommit the product.oid = current.oid++. Then in your DbContext class override the OnModelCreating method as so:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
modelBuilder.Entity<Product>().HasKey(p => p.oid);
Hope it helps!
Jan 06, 2013 04:05 AM|LINK
If I do this then how to I set the property oid? It is the primary key but I need to set it.
Jan 06, 2013 05:45 AM|LINK
this should work just ammend the code i gave to earlier to use this:
modelBuilder.Entity<Product>().HasKey(p => p.oid).Property(p => p.oid).HasDatabaseGeneratedOption(DatabaseGeneratedOption.none);
Then you manually increment it like you were in your first example.
Jan 06, 2013 02:38 PM|LINK
If you would be so kind, please post the full code code. Right now I interrpret your answer as adding the method then just before setting the oid as I posted I call this line. So basically I insert this line just before setting the oid and add the method
you posted to the context. Right?
How does this change if I have a composite key and the other PK is a string and is named CategoryName?
Jan 07, 2013 12:45 AM|LINK
How did you design your model entity?
And what about the primary key generated? Is that auto-generated?