Inserting Data to database using Repository in mvc4? unable to insert the multiple data? - entity-framework-4

I have two Entities billing and BillingDetail
in billing I am adding more than one time and after that I am adding data to BillingDetail finally I am Saving the Database. but when i checked database in billing table, it was containg only last data(only one row that was last updated)
How I supposed to solve this problem?
foreach ()
{
billingRepository.Insert(billModel);
}
billingDetailRepository.Insert(billDetailModel);
dbContext.Save();

When an entity is inserted is will be in attached state. Therefor Entity Framework will know it already exists in the context an not insert it again.
You can detach the entity and then insert it again to have it multiple times. But beware, after an insert PK fields are auto mapped to the entity.

Related

IOS Core Data Cascade Delete Issues

I found a question very similar to mine here, but it was un-replied to and unanswered so I will try again.
I may be missing something in regards to cascade deletes and core data. I am used to cascade deletes working as designed in RDBMS apps but having issues with core data.
I have an object record that get's inserted into entity via an "add form" called modally from a table view. No problem.
In another session I will insert objects into a related details entity (many) where there is a common loadID attribute in both. No problem.
In another session, I will call up the original table view to view the parent "loads", and swipe-delete, save the context, and the parent load gets deleted from the one side entity. No problem, (except apparently details objects in a many side entity do not get removed)
When I open the sqlite data source with a db manager, I see the child records (pay detail items) are being orphaned. I have double and triple checked the cascade delete settings in the relationships. Have tried different entity relationship settings combinations, but nothing seems to get the many records to automatically delete along with the parent record.
If you can't define corresponding keys in core data, how does core data know what belongs to what when you operate in multiple sessions (contexts) adding child objects to the many-side entity?
I don't know if I'm doing something wrong or missing a vital step prior to inserting new child objects in the many table, or doing something wrong or missing a step when deleting the parent object.
But I would suggest all with cascade deletes set to open your data file and be sure there are not orphaned objects (records)

oracle devart entity framework - added New column - now trigger system_id not changing to a unique new number?

oracle 10.4
devart dotConnect - 6.50...
MVC2 project - web page
User fills out form, then controller gets new entity, fills it out. saves database
System_id before saving = 0 (its an int/number - so no cannot be null)
Several other tables linked, so they have their own System_id as well.
When it gets saved to database, some trigger (there is a stored trigger for the table, which I only seam to understand as when system_id=null to be fired), a new Number is assigned for System_id.
This all worked fine.
Then I came along, and needed some updates.
Another field needed on this "main" table
(I have earlier, added columns to another table, with out issue)
Added column to this "main" table (restrict_to_me)
Now when it tries to save to database - it trys saving "system_id=0".
Linked tables, also make records with system_id=0
In entity framework designer - i can see the field system_id ENTITY_KEY=true and StoredGeneratedPatern=Idenity
So I can not see what I have done to stop somthing from working with the entity framework, except updating the entity framework.
Any direction much appricated
thanks
When you added the new field, did you drop the table and recreate it?
If you did that then you deleted the trigger at the same time. So when you recreate the table, you also need to recreate the trigger.
Try inserting data just using an SQL statement and see if the id is generated.
This was an Entity Framework issue, one many have already had.
Not every time, but some times, when updating the model, StoredGenereatedPattern being droped in a section.
http://www.ladislavmrnka.com/2011/03/the-bug-in-storegeneratedpattern-fixed-in-vs-2010-sp1/
When looking at fixes, did not understand that BOTH SSDL and CSDL parts stored in same text.
So look in upper part that it has StoredGenereated Pattern.

EF Database First - Mapping-error 3025

New to EF and trying something out with "Database first".
Error 3025: ... :Must specify mapping for all key properties
(PurchaseUsers.PurchaseUsersId) of table PurchaseUsers.
I have in my db 3 tables:
Purchases Participants PurchaseUsers
PurchaseId ParticipantId PurchaseUsersId
... ... PurchaseId
ParticipantID
The table PurchaseUsers is to know which participant(s) is(are) using a purchase.
At first I didn't had the PK on that table but then I got the following error when trying to save a Purchase.
After googling a bit I found out that I had to add a PK to avoid this error.
Unable to update the EntitySet 'PurchaseUsers' because it has a DefiningQuery
and no <InsertFunction> element exists in the <ModificationFunctionMapping> element
to support the current operation.
But adding the PK created the mapping-error and I just can't figure out how to solve this or create a mapping.
The table PurchaseUsers itself isn't visible in my .edmx model, but it's listed in the Store in the Model Browser.
Thanks.
UPDATE
Changed the name of a column in the database today. "Update model from database" added the new columnname to the table in the model, but did not remove the old one.
Had to start from scratch once again.
Looks like the update-function is not working very well.
This is weird. Updating the model from the database should make the model and the database to by in-sync. Try deleting and recreating the model from scratch.

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.

ASP.NET MVC Get ID of last added record

I'm using an MVC webform to insert a record into a database with several subrecords. In my code-behind I'm first creating a new main record using dataRepository.Add(xx). Now I need to add 5 subrecords that need the ID of the newly created record. How can I retrieve that?
Assuming xx is your model, and its primary key is Id you can get the Id of your inserted record like this:
// at this point xx.Id == null
db.XX.AddObject(xx);
db.SaveChanges();
// now: xx.Id > 0
int id = xx.Id;
If you are using an ORM such as Entity Framework you should be able to create the record and the associated records, link them by adding the associated records into a collection on the main object or setting them somehow and then call the save method on the context. This will do all the linking with ids etc. for you.
How are you doing data access?
You should probably submit all 5 records plus the main one all the way down to your datalayer, performing any validation on the way in your business layer. Then, depending on the implementation of your DL, save the main record, returning the ID, set the parent ID on the subrecords and save them. Do it all within a single transaction and you should be ok.
Please give more info on your data access layer.
If using MS SQL Server, you would use the Scope_Identity() within your stored procedure to get the last identity value inserted into an identity column. See this MSDN article
If using NHibernate you add them within the same session and NHibernate takes care of generating the SQL responsible for inserting the records with the correct Ids.

Resources