Error while Inserting data in loop pne by one using Entity Framework - entity-framework

while inserting records in a loop
The property "id" is part of the object's key information and cannot be modified
secProductionRepository.Add(tblSecProduction);
this.SaveChanges();
CODE
Controller : This is the Controller code from where i am calling method of Repository . Adding data into repository and calling function to insert. i think i have to initialize it every time with new keyword. But where should i do that.
SingleMaster objGetXMLData = _iSingleService.GetXMLData();
if (objGetXMLData._tblSecDoorXMLData != null)
{
for (int totalCount = 0; totalCount < objGetXMLData._tblSecDoorXMLData.Count; totalCount++)
{
_tblSecDoorsProduction.txtTongue = singleDoorModel.txtTongue;
_tblSecDoorsProduction.numFibMesh = Convert.ToInt32(singleDoorModel.chkBoxFibreMesh);
_tblSecDoorsProduction.dteDesDate = DateTime.Now;
_iSingleDoorService.UpdatetblSecDoorsProduction(_tblSecDoorsProduction, "Insert");
}
}
Repository : Here i am inserting new row into the table
public void UpdatetblSecDoorsProduction(tblSecDoorsProduction tblSecDoorsProduction, string Message)
{
var secDoorsProductionRepository = Nuow.Repository<tblSecDoorsProduction>();
tblSecDoorsProduction alreadyAttached = null;
if (Message == "Insert")
{
secDoorsProductionRepository.Add(tblSecDoorsProduction);
Nuow.SaveChanges();
}
}

Create new object each time in the loop. Updated code here:
for (int totalCount = 0; totalCount < objGetXMLData._tblSecDoorXMLData.Count; totalCount++)
{
tblSecDoorsProduction _tblSecDoorsProduction = new tblSecDoorsProduction();
_tblSecDoorsProduction.txtTongue = singleDoorModel.txtTongue;
_tblSecDoorsProduction.numFibMesh = Convert.ToInt32(singleDoorModel.chkBoxFibreMesh);
_tblSecDoorsProduction.dteDesDate = DateTime.Now;
_iSingleDoorService.UpdatetblSecDoorsProduction(_tblSecDoorsProduction, "Insert");
}

Related

Writing Test class for Currency Conversion Trigger

I need little assistance in writing a test class for this trigger that converts the record currency to org currency. Can anyone please assist/guide? Please.
trigger convertToEuro on CustomObject(before update) {
List<CurrencyType> currencyTypeList = [select id,IsoCode,ConversionRate from CurrencyType where isActive = true] ;
Map<String , Decimal> isoWithRateMap = new Map<String, Decimal>();
for(CurrencyType c : currencyTypeList) {
isoWithRateMap.put(c.IsoCode , c.ConversionRate) ;
}
for(CustomObject ce: trigger.new){
if(ce.CurrencyIsoCode != 'EUR' && isoWithRateMap.containsKey(ce.CurrencyIsoCode)){
ce.Amount_Converted__c = ce.ffps_iv__Amount__c/ isoWithRateMap.get(ce.CurrencyIsoCode);
}
}
}
#isTest(seealldata=false)
public class testConvertToEuro{
#testSetup
static void setupTest(){
List<CurrencyType> liCT = New List<CurrencyType>();
List<CustomObject> liCO = New List<CustomObject>();
Integer iCounter = 0;
liCT.add(new CurrencyType(IsoCode='EUR',ConversionRate=1,isActive=TRUE));
liCT.add(new CurrencyType(IsoCode='USD',ConversionRate=2,isActive=TRUE));
liCT.add(new CurrencyType(IsoCode='XXX',ConversionRate=3,isActive=TRUE));
liCT.add(new CurrencyType(IsoCode='YYY',ConversionRate=4,isActive=TRUE));
liCT.add(new CurrencyType(IsoCode='ZZZ',ConversionRate=5,isActive=TRUE));
for(Integer i=0; i<251; i++){
CustomObject co = New CustomObject(
CurrencyIsoCode = liCT[iCounter].IsoCode;
ffps_iv__Amount__c = liCT[iCounter].ConversionRate + .01;
);
if(iCounter < liCT.size() -1){
iCounter += 1;
}
else{
iCounter = 0;
}
}
insert liCT;
insert liCO;
}
static testmethod void runTest(){
setupTest();
List<CustomObject> liCustomObjectsToUpdate = New List<CustomObject>();
for(CustomObject co : [SELECT Id, ffps_iv__Amount__c, Amount_Converted__c from CustomObject]){
co.ffps_iv__Amount__c -= .01;
liCustomObjectsToUpdate.add(co);
}
test.startTest();
Update liCustomObjectsToUpdate;
test.stopTest();
System.assertEquals([SELECT Id, Amount_Converted__c FROM CustomObject LIMIT 1][0].Amount_Converted__c, 1);
}
}
I can't test this code without adding your custom object so it might have some errors. Please let me know what errors you are getting. If you want help debugging, you should provide the exact code being used and the exact error message.
It follows the basic pattern for testing update triggers:
Insert test data
Retrieve test data
Update records
Assert that the trigger generated the desired result

Dynamics CRM plugin -Pre Operation Update

I created a plug-in that calculates the pricing of the quote based on custom fields whenever update done on the quote entity.I executed the plugin on pre-opertaion update of the quote entity.I tried to debbug my plugin, it retrives null values.For example the value of the field "edm_CashAmount" contains 5000 but the code retrieved null. Kindly advise on the below. Thanks in advance.
namespace CRMPlugins.Plugins
{
using System;
using System.ServiceModel;
using Microsoft.Xrm.Sdk;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Crm.Sdk.Messages;
public class PrequoteUpdate : Plugin
{
public PrequoteUpdate()
: base(typeof(PrequoteUpdate))
{
base.RegisteredEvents.Add(new Tuple<int, string, string, Action<LocalPluginContext>>(20, "Update", "quote", new Action<LocalPluginContext>(ExecutePrequoteUpdate)));
}
protected void ExecutePrequoteUpdate(LocalPluginContext localContext)
{
if (localContext == null)
{
throw new ArgumentNullException("localContext");
}
Entity entity = null;
if (localContext.PluginExecutionContext.InputParameters.Contains("Target") && localContext.PluginExecutionContext.InputParameters["Target"] is Entity)
{
entity = (Entity)localContext.PluginExecutionContext.InputParameters["Target"];
}
else
{
return;
}
decimal instotal = 0;
Quote quote = entity.ToEntity<Quote>();
using (GeneratedEntities orgContext = new GeneratedEntities(localContext.OrganizationService))
{
var installements = (from b in orgContext.edm_installementSet
where b.GetAttributeValue<Guid>("edm_quote") == quote.QuoteId
select b);
foreach (var c in installements)
{
if (c.edm_Amount != null)
{
instotal += (decimal)c.new_Decimal;
}
}
}
decimal cash = 0;
if (quote.edm_CashAmount != null)
{
cash = Convert.ToDecimal(quote.GetAttributeValue<Money>("edm_cashamount").Value);
}
decimal check = 0;
if (quote.edm_CheckAmount != null)
{
check = Convert.ToDecimal(quote.GetAttributeValue<Money>("edm_checkamount").Value);
}
decimal credit = 0;
if (quote.edm_CreditCardAmount != null)
{
credit = Convert.ToDecimal(quote.GetAttributeValue<Money>("edm_creditcardamount").Value);
}
decimal gift = 0;
if (quote.new_GiftCard != null)
{
gift = Convert.ToDecimal(quote.GetAttributeValue<Money>("new_giftcard").Value);
}
decimal total = 0;
if (quote.TotalLineItemAmount != null)
{
total = Convert.ToDecimal(quote.GetAttributeValue<Money>("totallineitemamount").Value);
}
decimal currentbalane = 0;
if (quote.edm_CurrentBalane != null)
{
currentbalane = Convert.ToDecimal(quote.GetAttributeValue<Money>("edm_currentbalane").Value);
}
decimal DiscAmount = 0;
if (quote.DiscountAmount != null)
{
DiscAmount = Convert.ToDecimal(quote.GetAttributeValue<Money>("discountamount").Value);
}
decimal totalafterdiscount = total - DiscAmount;
decimal tax = (totalafterdiscount * 10) / 100;
decimal totalwithvat = totalafterdiscount + tax;
decimal paidamount = cash + check + credit + gift + instotal;
decimal remainingamount = totalwithvat - paidamount;
quote["edm_cashamount_1"] = new Money(tax);
quote["edm_totaltax"] = new Money(tax);
quote["edm_paidamount"] = new Money(paidamount);
quote["edm_remainingamount"] = new Money(remainingamount);
quote["edm_total"] = new Money(totalwithvat);
quote["edm_totalinstallements"] = new Money(instotal);
quote["edm_checkamount_1"] = new Money(totalwithvat);
}
}
}
for update plugins, if the value has not been changed then it will not appear in the target entity. Therefore you should create a pre entity image an include these values, or you can create a post entity image to see the state of the entity after the changes will be applied

How to fetch table data in Entity Framework and assign it to any Button or Texbox without using where condition

How I can do this in Entity Framework?
sSQL = "SELECT CategoryName FROM CategorySetup";
if (Conn.State == ConnectionState.Closed) { Conn.Open(); }
cmd = new SqlCommand(sSQL, Conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
btn_Chicken.Text = dt.Rows[0]["CategoryName"].ToString();
btn_Beef.Text = dt.Rows[1]["CategoryName"].ToString();
btn_Rice.Text = dt.Rows[2]["CategoryName"].ToString();
btn_Drink.Text = dt.Rows[3]["CategoryName"].ToString();
How I can do same thing in Entity Framework 5.0? If anybody knows, please tell me I'm searching it on google but cant find it, I'm new to ASP.NET MVC and Entity Framework
Once you have your EF context set up, fetching the data per se is simple:
List<CategorySetup> listOfCat = yourDbContext.CategorySetup;
But the main question is: how do you know which of those objects you got back from the database table corresponds to the button in your GUI?? Do you have a column in your database table to order your data by? So that you always now row #0 is for btn_Chicken, row #1 is for btn_Beef ? Or is there a column on the CategorySetup table to allows you to find out which CategorySetup object to use for which button?
POS_EF_Project.DataBase_Create.POS_Context db = new POS_EF_Project.DataBase_Create.POS_Context();
Button[] buttonArray = new Button[9];
public frmTesting()
{
InitializeComponent();
}
// Display Function
public void Display(int i)
{
string index = buttonArray[i].Tag.ToString();
var itm = db.ItemSetups.Where(c => c.CatagoryCode == index).OrderBy(c => c.ItemName);
int iCounter = 0;
foreach (ItemSetup t in itm)
{
fp_Items.Sheets[0].Rows.Count = iCounter + 1;
fp_Items.Sheets[0].Cells[iCounter, 0].Text = t.ItemCode;
fp_Items.Sheets[0].Cells[iCounter, 1].Text = t.ItemName;
fp_Items.Sheets[0].Cells[iCounter, 2].Text = t.Price.ToString();
iCounter++;
}
}
private void btn_Start_Click(object sender, EventArgs e)
{
var cat = db.Categorys.ToList();
int horizotal = 6;
int vertical = 96;
for (int i = 0; i < buttonArray.Length; i++)
{
int index = i;
buttonArray[i] = new Button();
buttonArray[i].Size = new Size(168, 40);
buttonArray[i].Location = new Point(horizotal, vertical);
buttonArray[i].TextAlign = ContentAlignment.MiddleLeft;
buttonArray[i].Text = cat[i].CatagoryName;
buttonArray[i].Tag = cat[i].CategoryCode;
buttonArray[i].ImageAlign = ContentAlignment.MiddleRight;
buttonArray[i].Image = (Image)Properties.Resources.ResourceManager.GetObject("Basket");
if ((i + 1) % 9 == 0) horizotal = 6;
else vertical += 42;
buttonArray[i].Click += (sender1, ex) => this.Display(index);
this.Controls.Add(buttonArray[i]);
}
}
}
}

EF : related entities are set as INSERT instead of being only referenced to the added entity

I tried to find an answer through the related questions I got but I didn't see the same situation I have now. I a beginner with this framework.
The thing is that in the DB the TopicFeedbackType is always referred but TopicNavigatedUrl and Product are always inserted event if I attach the entity. What am I doing wrong? I attach the found entity to the correct entity set name. The entity gets attached. I noticed that before the p_TopicQuickFb have one of its property updated by an attached entity, its EntityKey is null, but when the currentNavUrl(for example) is set, the EntityKey of p_TopicQuickFb is not null anymore. Its value is "EntitySet=TopicQuickFeedbacks" but there is no id.
I am really lost in there.
public void AddTopicQuickFeedback(TopicQuickFeedback p_TopicQuickFb, string p_SessionID)
{
TopicFeedbackType currentType = this.GetTopicFeedbackType(p_TopicQuickFb.TopicFeedbackType.FeedbackType);
bool currentTypeAttached = false;
TopicNavigatedUrl currentNavUrl = this.GetTopicNavigatedUrl(p_TopicQuickFb.TopicNavigatedUrl.Url);
bool currentNavUrlAttached = false;
Product currentProduct = this.GetProduct(p_TopicQuickFb.Product.Name, p_TopicQuickFb.Product.MajorVersion, p_TopicQuickFb.Product.MinorVersion);
bool currentProductAttached = false;
using (COHFeedbackEntities context = GetObjectContext())
{
TopicFeedback tf = GetTopicFeedback(p_SessionID, context);
if (tf != null)
{
if (currentType != null)
{
p_TopicQuickFb.TopicFeedbackType = null;
context.AttachToOrGet<TopicFeedbackType>("TopicFeedbackTypes", ref currentType);
currentTypeAttached = true;
p_TopicQuickFb.TopicFeedbackType = currentType;
}
if (currentNavUrl != null)
{
p_TopicQuickFb.TopicNavigatedUrl = null;
context.AttachToOrGet<TopicNavigatedUrl>("TopicNavigatedUrls", ref currentNavUrl);
currentNavUrlAttached = true;
p_TopicQuickFb.TopicNavigatedUrl = currentNavUrl;
}
if (currentProduct != null)
{
p_TopicQuickFb.Product = null;
context.AttachToOrGet<Product>("Products", ref currentProduct);
currentProductAttached = true;
p_TopicQuickFb.Product = currentProduct;
}
tf.TopicQuickFeedbacks.Add(p_TopicQuickFb);
context.SaveChanges();
context.Detach(tf);
if (currentNavUrlAttached)
{
context.TopicNavigatedUrls.Detach(currentNavUrl);
}
if (currentProductAttached)
{
context.Products.Detach(currentProduct);
}
if (currentTypeAttached)
{
context.TopicFeedbackTypes.Detach(currentType);
}
}
}
}
I found the method in this post : Is is possible to check if an object is already attached to a data context in Entity Framework?
public static void AttachToOrGet<T>(this System.Data.Objects.ObjectContext context, string entitySetName, ref T entity)
where T : IEntityWithKey
{
System.Data.Objects.ObjectStateEntry entry;
// Track whether we need to perform an attach
bool attach = false;
if (
context.ObjectStateManager.TryGetObjectStateEntry
(
context.CreateEntityKey(entitySetName, entity),
out entry
)
)
{
// Re-attach if necessary
attach = entry.State == EntityState.Detached;
// Get the discovered entity to the ref
entity = (T)entry.Entity;
}
else
{
// Attach for the first time
attach = true;
}
if (attach)
{
context.AttachTo(entitySetName, entity);
}
}
Test method:
User user = new User(true, false, false);
string commentStr = "This is my comment";
Product product = new Product("ProductName", 7, 0);
TopicFeedbackComment commFeedback = new TopicFeedbackComment(commentStr, new TopicNavigatedUrl("http://testurl.com/test0"), product);
TopicFeedback feedback = new TopicFeedback(sessionID, user, FeedbackState.New);
provider.AddTopicFeedback(feedback);
TopicFeedback addedFeedback = provider.RetrieveTopicFeedback(sessionID);
provider.AddTopicFeedbackComment(commFeedback, sessionID);
Running this again and again do just INSERT to the
Can't post images so I can provide schema it if necessary.
My answer is in my last comment. I found it by myself.
If someone would like to comment why it's working this way it would be nice! :)

Entity Framework - Saving child entities on update

I have an Invoice entity and it has child InvoiceLog entities. When I first create an Invoice and add its InvoiceLog entities and save, it works fine. However, if I then edit the Invoice and try to add additional InvoiceLog entities, it completely ignores the new InvoiceLog entities and doesn't save them at all. Any ideas what I'm doing wrong?
//POST: /Secure/Invoices/Save/
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Save(Invoice invoice)
{
invoice.UpdateDate = DateTime.Now;
invoice.DeveloperID = Developer.DeveloperID;
invoice.InvoiceStatusID = (int)Enums.InvoiceStatus.Open;
if (invoice.InvoiceID == 0)
{//inserting new invoice.
DataContext.InvoiceData.Insert(invoice);
}
else
{//attaching existing invoice.
DataContext.InvoiceData.Attach(invoice);
}
AddHours(invoice);
//save changes.
DataContext.SaveChanges();
//redirect to invoice list.
return RedirectToAction("Index");
}
private void AddHours(Invoice invoice)
{
//get existing logs.
IQueryable<InvoiceLog> existingLogs = null;
if(invoice.InvoiceID > 0)
{
existingLogs = DataContext.InvoiceData.GetLogs(invoice.InvoiceID);
}
//create new logs.
var numDays = invoice.EndDate.Subtract(invoice.StartDate).TotalDays;
for (int k = 0; k <= numDays; k++)
{
//check if log already exists.
var existingLog = existingLogs.ToList().FindIndex(l => l.LogDate == invoice.StartDate.AddDays(k));
if (existingLog == -1)
{
//add new log.
var log = new InvoiceLog();
log.CreateDate = DateTime.Now;
log.UpdateDate = DateTime.Now;
log.Hours = 0;
log.InvoiceID = invoice.InvoiceID;
log.LogDate = invoice.StartDate.AddDays(k);
invoice.InvoiceLogs.Add(log);
}
}
}
Thanks,
Justin
You can try to add InvoiceLogs items before attaching the invoice:
else
{//attaching existing invoice.
AddHours(invoice);
DataContext.InvoiceData.Attach(invoice);
}