Is it possible to make Entity Framework insert primary key that I given? - entity-framework-6

I forced to work with database where tables haven't auto increment. And I can't alter it. I want to insert entity using Entity Framework. I create an object of this entity and manually set it's Id field (primay key) and then make Add and SaveChanges. But I see in log, that EF clear the value of DbParameter for Id field. Is there any solution for this?

You can add an annotation of fluent configuration to tell EF the keys are manual. See Entering keys manually with Entity Framework. You could also add a custom convention to handle globally: Convention for DatabaseGeneratedOption.None

Related

MVC 5 EF 6 Insert Multiple Rows SaveChanges

I am trying to insert multiple rows using the following code. SaveChanges() works for the first record but if fails when it tries the next one. My guess is that each time it is trying to insert all records. Not sure if this is correct or not, and if it is correct how can I change the code to make it correct. Following is my code:
Contrroller:
foreach(var m in pms)
{
_pmService.AddPms(m);
}
And in _pmService.AddPms:
_pmRepository.Add(pm);
_pmRepository.SaveChanges();
_pmRepository.Add (actually this is from BaseRepository and pmRepository extends this Base)
_ctx.Set<T>().Add(entity);
Finally, here is my SaveChanges() (again this is also from BaseRepostiroy)
_ctx.ChangeTracker.DetectChanges();
return _ctx.SaveChanges();
So in controller, I am looping through each entry, and then calling Add. The Add in service is calls Add in BaseRepository and then it does the SaveChanges(). For first record it works without any issues but 2nd record onwards it fails. And following is the error:
"Saving or accepting changes failed because more than one entity of type XXXXXXXXXXXXX have the same primary key value. Ensure that explicitly set primary key values are unique. Ensure that database-generated primary keys are configured correctly in the database and in the Entity Framework model. Use the Entity Designer for Database First/Model First configuration. Use the 'HasDatabaseGeneratedOption\" fluent API or 'DatabaseGeneratedAttribute' for Code First configuration."
And I am using DatabaseFirst approach.
I found the answer it is with StoreGeneratedPattern. I had to set this Identity in edmx file for the primary key field and it worked.
StoreGeneratedPattern="Identity"

How does Breeze handle database column defaults?

I can't find any info about this in the documentation, so I will ask here. How does breeze handle database column defaults? I have required columns in my database, but there are also default static values supplied for these in the database column definitions. Normally, I can insert null into these columns, and the new records will get the default. However, breeze doesn't seem to be aware of database column defaults, and the entities that have null in these columns fail validation on saving.
Thanks,
Mathias
Try editing the edmx xml by adding StoreGeneratedPattern = "Computed" attribute to the column with default value in the DB.
Edit:
Actually, before doing editing the xml, try setting the StoreGeneratedPattern property to Computed in the model editor itself.
Update:
This was fixed in Breeze 1.4.6 ( or later), available now.
Original Post:
There is currently in a bug in Breeze that should be fixed in the next release, out in about week. When this fix gets in then breeze will honor any defaultValues it finds in the EntityFramework data model.
One problem though is while it is easy to get 'defaultValues' into a Model First Entity Framework model via the properties editor, it's actually difficult to get it into a Code First EF model, unless you use fluent configuration. Unfortunately, EF ignores the [DefaultValue] attribute when constructing Code First model metadata.
One workaround that you can use now is to poke the 'defaultValue' directly onto any dataProperty. Something like:
var customerType = myEntityManager.metadataStore.getEntityType("Customer");
var fooProperty = customerType.getProperty("foo");
fooProperty.defaultValue = 123;

Entity Framework: how do I add a field to my entity to match the store procedure result

I have an entity (Org) in my Entity Framework that has a foreign key with a table that is in another database (BusinessUnit). We need the foreign key to get the description of the BusinessUnit linked with the Org. In the past (old project without Entity Framework) we were using a stored procedure to return all the information about this entity, including the BusinessUnit description, using a join. So now my problem is how to display the same information than before using Entity Framework.
I've tried, once I load my Org entity from database, to make a loop accessing to BusinessUnit to get the description for each Org, but this is too slow. My other idea was use a store procedure, but I need an extra field on my entity and Entity Frameworks gives me an 3004 error: No mapping specified for my property. I was thinking to use a complex type, but I'm not sure if it's what I need keeping in mind I have to add just a field to my entity. In that case, could I use the complex type just for "select" operations and keep my original entity for the rest of CRUD operations?
How should I proceed?
Thanks.
EF is not able to execute queries across multiple databases. If you need to perform such query you must either use database view and map the view as a new entity (it will be readonly - making it updatable requires mapping insert, update and delete stored procedures) or divide your data querying into two separate parts to load data from both databases. Divided querying can either use two contexts or you can get data from the second database using stored procedure.
The reason why you got the error is that you added the property in EDMX. EDMX can contain only properties mapped to your first database. EDMX generates entity code as partial classes If you need property manually populated from the second database you have to create your partial part (partial class) for entity and add the property in code.

Entity Framework 4 Change Audit

I have a web application using EF4. I am somewhat new to EF and now trying to implement change Audit.I tried to do this by trapping the SavingChanges event of the Context Class as below
partial void OnContextCreated()
{
this.SavingChanges += new EventHandler(TicketContainer_SavingChanges);
}
So the event handler accesses the changed records by the following
this.ObjectStateManager.GetObjectStateEntries(
EntityState.Added | EntityState.Modified);
This works fine and I am creating column level audit for selected tables. Every table/entity has an ID field which is an identifier with columnName="ID". So in my audit routine I simply accesses data from column with name "Id" to get the ID of audited record.
The problem I face is during insert . The new record has no ID yet as it is an identity column in the database and is always 0.
One solution I can think of is using GUID for all Ids.But is there a way to implement this using standard int32 Identity Ids?
thanks
When we insert data through EF the identity column is not generted while insertion. To get the Id of Identity columns we have to insert the data first then only we can get the Id of coulmn.
please go through the below which might be helpful to you.
http://www.codeproject.com/KB/database/ImplAudingTrailUsingEFP1.aspx
I don't now how many entities you have but in our own implementation of audit tracking we created a specific audit entity for each entity so we could link them together trough navigational properties and let the database set the identity keys.
If you use inheritance for your audit entities it's quit easy to query them.
Hope this helps :)
Identity columns are not generated while insertion. Once data is inserted then only you can get identity column data in EF. So, you can try some work around by getting Id after insertion and then populating audit table with that Id.

UpdateModel() cannot assign new value to navigation property (entity reference)

This happens in ASP.NET MVC 2, .NET 4 (EF 4). My Address entity has a reference to the Post reference. Zip is the primary key of the Post entity. Another property in Post entity is CityName. In my views I allow users to change the CityName for the address which automatically (via jquery) loads up the corresponding Zip and stores it inside a hidden field.
When posted, both values are posted fine and binded to the Address's Post reference. But UpdateModel() fails to update them. It says that the Zip is part of the entity's Entity Key and cannot be changed.
I would gladly load up the Post entity by the new Zip and manually assign it to the existing Address but for all other properties I stall want to rely on UpdateModel().
How can I achieve that? One would think that in EF4 stuff like this has been resolved..
By default the entity framework generated classes put restrictions on changing primary key values. This is good. You shouldn't change a PK for any reason at all. Changing PKs outside of add scenarios has pretty huge ramifications for state tracking and the general health of your system.
To solve this problem you want to tell UpdateModel not to update your primary keys using the exclude parameter.

Resources