Add parent row and add child for that new parent row - asp.net

i am creating new record in 'Timecard' table and at the same time i want to create one record in 'TimecardStatusTrack' table using entity framework. i am able to create parent record but while adding child record i am getting exception. the code i have written is like
var fEmpManager = DependencyContainer.GetInstance<IBusinessService<FacilityEmployee>>();
int timecardStatusDidNotWork =
Convert.ToInt32(GeneralCodeId.TimeCardStatusDidNotWork, CultureInfo.InvariantCulture);
Timecard timecard = new Timecard();
TimecardStatusTrack timecardStatus = new TimecardStatusTrack();
try
{
var fEmp = fEmpManager.Where(w => w.JobId == jobId && w.AgencyBiddingProfile.AgencyCandidateId == agencyCandidateId).FirstOrDefault();
timecard.JobId = jobId;
timecard.AgencyCandidateId = agencyCandidateId;
timecard.WeekStartDate = Convert.ToDateTime(weekStartDate, CultureInfo.InvariantCulture);
timecard.WeekEndDate = Convert.ToDateTime(weekEndDate, CultureInfo.InvariantCulture);
timecard.FacilityEmployeeId = fEmp.Id;
timecard.FacilityId = fEmp.FacilityId;
timecard.TimecardStatusGCId = timecardStatusDidNotWork;
timecard.AddUser = SessionManager.AuthorizedInfo.UserId;
timecard.AddDate = DateTime.Now;
timecardStatus.TimecardStatusGCId = timecardStatusDidNotWork;
timecardStatus.AddUser = SessionManager.AuthorizedInfo.UserId;
timecardStatus.AddDate = DateTime.Now;
timecardStatus.UpdatedBy = SessionManager.AuthorizedInfo.UserId;
timecardStatus.Comments = string.Empty;
_ViewTimeCardBusibessService.Create(timecard);
timecard.TimecardStatusTracks.Add(timecardStatus);
_ViewTimeCardBusibessService.Update(timecard);
}
catch (Exception ex)
{
HandleValidationErrors(ex);
}
finally
{
DependencyContainer.ReleaseInstance(fEmpManager);
}

Related

how to Add list of products from cart?

dears,
i have an API working with ASP.Net Core 3.1 posting orders
i want to post order head and get all items from another api in cart items and post it in order items my code as below
[HttpPost("addOrderHead")]
public async Task<ActionResult<OrderDto>> Posting(OrderDto dto)
{
try
{
if (dto == null)
{
return BadRequest(ModelState);
}
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var mappedEntities = _mapper.Map<Order>(dto);
_orderRepository.Add(mappedEntities);
if (await _orderRepository.Save())
{
int id = mappedEntities.OrderID;
var cartItems = await _cartItemRepository.GetCartItems(mappedEntities.ApplicationUserId);
var cartDto = new CartItemDto();
foreach(var item in cartItems)
{
cartDto.ItemID = item.ItemID;
cartDto.ItemLookupCode = item.ItemLookupCode;
cartDto.CategoryID = item.CategoryID;
cartDto.DepartmentID = item.DepartmentID;
cartDto.itemDescription = item.itemDescription;
cartDto.SubDescription3 = item.SubDescription3;
cartDto.Quantity = item.Quantity;
cartDto.Weight = item.Weight;
cartDto.SnapShotPrice = item.SnapShotPrice;
cartDto.StoreId = item.StoreId;
cartDto.barcode = item.barcode;
cartDto.Email = item.Email;
cartDto.ItemImage = item.ItemImage;
};
var items = new OrderItems()
{
OrderId = id,
ItemID = cartDto.ItemID,
ItemLookupCode = cartDto.ItemLookupCode,
CategoryID = cartDto.CategoryID,
DepartmentID = cartDto.DepartmentID,
itemDescription = cartDto.itemDescription,
SubDescription3 = cartDto.SubDescription3,
Quantity = cartDto.Quantity,
Weight = cartDto.Weight,
SnapShotPrice = cartDto.SnapShotPrice,
StoreId = cartDto.StoreId,
barcode = cartDto.barcode,
Email = cartDto.Email,
ItemImage = cartDto.ItemImage,
};
_orderItemsRepository.Add(items);
await _orderItemsRepository.Save();
return Ok(id);
}
return BadRequest(ModelState);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.InnerException.Message);
}
}
every time i run this api order header added successfully and order items add first item only
which cart items return with array of items ,
can any one help me in that ,
You need to put Add (and maybe .Save()) inside the foreach:
var cartItems = await _cartItemRepository.GetCartItems(mappedEntities.ApplicationUserId);
foreach(var item in cartItems)
{
var cartDto = new CartItemDto(); // inside foreach
cartDto.ItemID = item.ItemID;
....
var item = new OrderItems() // one item - not: items
{
OrderId = id,
ItemID = cartDto.ItemID,
...
ItemImage = cartDto.ItemImage,
};
_orderItemsRepository.Add(item); // add item before moving to next item.
}
await _orderItemsRepository.Save();
BTW. I'm not sure why you need cartDto; I think you can eliminate it:
var cartItems = await _cartItemRepository.GetCartItems(mappedEntities.ApplicationUserId);
foreach(var item in cartItems)
{
var item = new OrderItems() // one item - not: items
{
OrderId = id,
ItemID = item.ItemID,
...
ItemImage = item.ItemImage,
};
_orderItemsRepository.Add(item); // add item before moving to next item.
}
await _orderItemsRepository.Save();
The code is not correct.In the below line you it should be List instead of object
var cartItems = await _cartItemRepository.GetCartItems(mappedEntities.ApplicationUserId);
var cartDtoList = new List<CartItemDto>();
foreach(var item in cartItems)
{
carDto carDto= new CarDto();
cartDto.ItemID = item.ItemID;
cartDto.ItemLookupCode = item.ItemLookupCode;
cartDto.CategoryID = item.CategoryID;
cartDto.DepartmentID = item.DepartmentID;
cartDto.itemDescription = item.itemDescription;
cartDto.SubDescription3 = item.SubDescription3;
cartDto.Quantity = item.Quantity;
cartDto.Weight = item.Weight;
cartDto.SnapShotPrice = item.SnapShotPrice;
cartDto.StoreId = item.StoreId;
cartDto.barcode = item.barcode;
cartDto.Email = item.Email;
cartDto.ItemImage = item.ItemImage;
carDtoList.Add(carDto)
};
Similarly the orderItems will also be list.
The other simplest solution is to put all the things inside foreach loop like this
foreach(var item in cartItems)
{
cartDto.ItemID = item.ItemID;
cartDto.ItemLookupCode = item.ItemLookupCode;
cartDto.CategoryID = item.CategoryID;
cartDto.DepartmentID = item.DepartmentID;
cartDto.itemDescription = item.itemDescription;
cartDto.SubDescription3 = item.SubDescription3;
cartDto.Quantity = item.Quantity;
cartDto.Weight = item.Weight;
cartDto.SnapShotPrice = item.SnapShotPrice;
cartDto.StoreId = item.StoreId;
cartDto.barcode = item.barcode;
cartDto.Email = item.Email;
cartDto.ItemImage = item.ItemImage;
var items = new OrderItems()
{
OrderId = id,
ItemID = cartDto.ItemID,
ItemLookupCode = cartDto.ItemLookupCode,
CategoryID = cartDto.CategoryID,
DepartmentID = cartDto.DepartmentID,
itemDescription = cartDto.itemDescription,
SubDescription3 = cartDto.SubDescription3,
Quantity = cartDto.Quantity,
Weight = cartDto.Weight,
SnapShotPrice = cartDto.SnapShotPrice,
StoreId = cartDto.StoreId,
barcode = cartDto.barcode,
Email = cartDto.Email,
ItemImage = cartDto.ItemImage,
};
_orderItemsRepository.Add(items);
await _orderItemsRepository.Save();
return Ok(id);
}

how to solve error like "Cannot implicitly convert type"?

Code:
public IEnumerable<InvoiceStringData> GetInvoiceByID(string orderID)
{
var orderId = Convert.ToInt32(orderID);
ResponseDetails jsonRes = new ResponseDetails();
List<string> campaignidByProdid = new List<string>();
Productlevelcharges prodlevel = new Productlevelcharges();
List<Productlevelcharges> lstprodlevel = new
List<Productlevelcharges>();
List<OrderVM> lstorvm = new List<OrderVM>();
List<ProductMaster> lstpmvm = new List<ProductMaster>();
List<OrderDetailsVM> lstodvm = new List<OrderDetailsVM>();
List<ProductVariant> lstpvvm = new List<ProductVariant>();
List<CampaignProductMapper> lstcmvm = new
List<CampaignProductMapper>();
List<CampaignVm> lstcm = new List<CampaignVm>();
List<InvoiceStringData> Bill = new List<InvoiceStringData>();
InvoiceStringData InvoiceStringData = new InvoiceStringData();
var orderChargId = _context.Orderlevelcharges.Where(a => a.OrderId == orderId).Select(a => a.OrderChargeId).FirstOrDefault();
var orderCharge = orderChargId.ToString();
var lst = CalculateUnitPrice(orderCharge, orderID);
var result = (from v in lst
group v by new
{
v.InvoiceDate,
v.InvoiceNo,
v.NetAmount,
v.TotalAmount,
v.SaveAmount
} into order
select new
{
invoiceDate = order.Key.InvoiceDate,
netAmount = order.Key.NetAmount,
totalAmount = order.Key.TotalAmount,
saveAmount = order.Key.SaveAmount,
// productMasterlst=order
_invoice = new
{
product = order.Select(o => new {
o.productName, o.UnitPrice, o.Quantity, o.UnitOfMeasure, o.hsnCode,
o.Weight, o.Tax1Sgst, o.Tax2Cgst, o.Tax3Igst })
}
}).ToList();
return result;
}
error:
CS0266 Cannot implicitly convert type
'System.Collections.Generic.List<> product> _invoice>>' to 'System.Collections.Generic.IEnumerable'. An explicit conversion exists (are you missing a cast?) Payment.API D:\Consumer Billing\MRU 15-05-18 10.47\MRU Current\src\Services\Payment\Payment.API\BAL\Repository\InvoiceRepo.cs 131 Active

Join two dynamic Linq in Asp.net

I have used linq to store data, below is the code:
var result = (dynamic)null;
var serviceData = (dynamic)null;
var userData = (dynamic)null;
/****Linq 1*****/
serviceData= dtPasscode.AsEnumerable().Select(m => new
{
ACCOUNT_ID = intAccountId,
SUB_ACC_ID = m.Field<string>("ACCOUNT_ID_ALIAS")
});
/**Linq 2**/
userData = DisplyCustomerDetails(Convert.ToInt64(strSubAccountID));
result = serviceData.Concat(userData);
And another linq through function:
/**Function**/
System.Data.EnumerableRowCollection DisplyCustomerDetails(Int64 intAccountId)
{
var result = (dynamic)null;
/** Data Display if no service avaiable **/
IAccount_BL objAccount_BL = new Account_BL();
Customer objCustomer = new Customer();
DataTable dtCustomer = null;
int intErrorCount = 0;
objCustomer.Account_Id = Convert.ToInt64(intAccountId);
dtCustomer = objAccount_BL.GetCustomerDetails(objCustomer, ref intErrorCount);
objAccount_BL = null;
objCustomer = null;
if (intErrorCount == 0)
{
if (dtCustomer != null)
{
if (dtCustomer.Rows.Count > 0)
{
result = dtCustomer.AsEnumerable().Select(m => new
{
ACCOUNT_ID = intAccountId,
SUB_ACC_ID = m.Field<string>("ACCOUNT_ID_ALIAS")
});
}
}
}
return result;
}
I wanted to join both the result of Linq1 & Linq2, I tired Concat & Union, getting below error
'System.Data.EnumerableRowCollection<<>f__AnonymousTypea>' does not contain a definition for 'Concat'
To Concat both enumerables must of the same class; you cannot use anonymous classes. Define a class that has the two fields and change the code to Select them.
Also, don't use ... = (dynamic) null; just assign the variable directly
var serviceData= dtPasscode ...
var userData = DisplyCustomerDetails ...
var result = serviceData.Concat(userData);

How to perform Rollback in asp.net when using Stored Procedure

I want to insert data into 12 different tables on a single click of a button. For this I am using single stored procedure. But my problem is when I am doing this and if there is any exception occurs my data is getting inserted partially i.e values is getting inserted in some tables and some remains empty and due to this problem occurs since all are related to one another. So wanted to know is there any way to perform Rollback so that if any exception occurs entire query is rolled back and data is not inserted in any of the table.
This is the code I am currently using for inserting values.
public int Sp_InsertUpdateDelete(string s, SqlParameter[] spa)
{
SqlConnection sc = new SqlConnection(cs);
sc.Open();
SqlCommand scm = new SqlCommand(s, sc);
scm.CommandType = CommandType.StoredProcedure;
foreach (SqlParameter sql in spa)
{
scm.Parameters.Add(sql);
}
int k = scm.ExecuteNonQuery();
sc.Close();
return k;
}
protected void btnHostingSubmit_Click(object sender, EventArgs e)
{
string select = "select * from tbl_Hosting where Customer_Id='" + ddlCustomerName.SelectedValue + "'";
DataSet s = gs.select(select);
if (s.Tables[0].Rows.Count > 0)
{
Response.Write("<script>alert('Customer Already Exist');</script>");
}
else
{
if (ddlHosting.SelectedValue == "Yes")
{
SqlParameter[] spa = new SqlParameter[29];
spa[0] = new SqlParameter("#Customer_Id", Convert.ToInt16(ddlCustomerName.SelectedValue));
spa[1] = new SqlParameter("#Type", 2);
//Hosting
if (txtHostingSDate.Text == "" || txtHostingSDate.Text == null)
{
spa[2] = new SqlParameter("#Hosting_start_date", null);
}
else
{
spa[2] = new SqlParameter("#Hosting_start_date", Convert.ToDateTime(txtHostingSDate.Text));
}
if (txtHosingEDate.Text == "" || txtHosingEDate.Text == null)
{
spa[3] = new SqlParameter("#Hosting_end_date", null);
}
else
{
spa[3] = new SqlParameter("#Hosting_end_date", Convert.ToDateTime(txtHosingEDate.Text));
}
spa[4] = new SqlParameter("#Hosting_provider", ddlHostingPro.SelectedItem.ToString());
spa[5] = new SqlParameter("#Hosting_type", ddlHostingType.SelectedItem.ToString());
spa[6] = new SqlParameter("#Hosting_server", ddlHostingServer.SelectedItem.ToString());
spa[7] = new SqlParameter("#Hosting_total_id", Convert.ToInt16(txtHostingId.Text));
spa[8] = new SqlParameter("#Hosting_mail_tracking", ddlHostingMailTracking.SelectedItem.ToString());
spa[9] = new SqlParameter("#Hosting_mail_tracking_users", Convert.ToInt16(txtHostingMtUser.Text));
spa[10] = new SqlParameter("#Hosting_dns", ddlHostingDns.SelectedItem.ToString());
spa[11] = new SqlParameter("#Hosting_mail", ddlHostingMail.SelectedItem.ToString());
spa[12] = new SqlParameter("#Hosting_web", ddlHostingWeb.SelectedItem.ToString());
spa[13] = new SqlParameter("#Hosting_manage_dns", ddlHostingMngDns.SelectedItem.ToString());
if (ddlHostingDns.SelectedValue == "No" && (ddlHostingMail.SelectedValue == "Yes" || ddlHostingWeb.SelectedValue == "Yes"))
{
spa[14] = new SqlParameter("#Hosting_ns1", txtNS1.Text);
spa[15] = new SqlParameter("#Hosting_ns2", txtNS2.Text);
}
else
{
spa[14] = new SqlParameter("#Hosting_ns1", ddlHostingNS1.SelectedItem.ToString());
spa[15] = new SqlParameter("#Hosting_ns2", ddlHostingNS2.SelectedItem.ToString());
}
spa[16] = new SqlParameter("#Hosting_rec_ip", txtHostingARecordIp.Text);
spa[17] = new SqlParameter("#Hosting_mx_rec1", txtMXRecord1.Text);
spa[18] = new SqlParameter("#Hosting_mx_rec2", txtMXRecord2.Text);
spa[19] = new SqlParameter("#Hosting_mx_ip1", txtHostingMxIp1.Text);
spa[20] = new SqlParameter("#Hosting_space", ddlHostingSpace.SelectedItem.ToString());
spa[21] = new SqlParameter("#Hosting_mx_ip2", txtHostingMxIp2.Text);
spa[22] = new SqlParameter("#Hosting_data_transfer", ddlhostingDataTrans.SelectedItem.ToString());
spa[23] = new SqlParameter("#Hosting_manage_dns_amt", txtHostingMangDnsAmt0.Text);
spa[24] = new SqlParameter("#Hosting_amt", txtHostingAmt0.Text);
spa[25] = new SqlParameter("#Hosting_c_ns1", txtHostingNS1.Text);
spa[26] = new SqlParameter("#Hosting_c_ns2", txtHostingNS2.Text);
spa[27] = new SqlParameter("#Hosting_c_ns3", txtHostingNS3.Text);
spa[28] = new SqlParameter("#Hosting_c_ns4", txtHostingNS4.Text);
int k = gs.Sp_InsertUpdateDelete("Sp_Hosting", spa);
if (k > 0)
{
Response.Write("<script>alert('Hosting Added Success');</script>");
}
Clear();
}
using(SqlConnection conn = new SqlConnection())
{
try
{
conn.Open();
SqlTransaction tran = conn.BeginTransaction("Transaction1");
Cmd = new SqlCommand(sQuery, Conn);
Cmd.Transaction = tran;
//Your Code
tran.Commit(); //both are successful
}
catch(Exception ex)
{
//if error occurred, reverse all actions. By this, your data consistent and correct
tran.Rollback();
}
}
https://msdn.microsoft.com/en-us/library/a90c30fy.aspx
You need to modify your Stored procedure and use Transactions for this feature.
Something like this:
DECLARE #TranName VARCHAR(20);
SELECT #TranName = 'MyTransaction';
BEGIN TRANSACTION #TranName;
USE AdventureWorks2012;
DELETE FROM AdventureWorks2012.HumanResources.JobCandidate
WHERE JobCandidateID = 13;
COMMIT TRANSACTION #TranName;
GO
MSDN Reference

How to differentiate between two similar fields in Linq Join tables

How to differentiate between two select new fields e.g. Description
c.Description and lt.Description
DataTable lDt = new DataTable();
try
{
lDt.Columns.Add(new DataColumn("AreaTypeID", typeof(Int32)));
lDt.Columns.Add(new DataColumn("CategoryRef", typeof(Int32)));
lDt.Columns.Add(new DataColumn("Description", typeof(String)));
lDt.Columns.Add(new DataColumn("CatDescription", typeof(String)));
EzEagleDBDataContext lDc = new EzEagleDBDataContext();
var lAreaType = (from lt in lDc.tbl_AreaTypes
join c in lDc.tbl_AreaCategories on lt.CategoryRef equals c.CategoryID
where lt.AreaTypeID== pTypeId
select new { lt.AreaTypeID, lt.Description, lt.CategoryRef, c.Description }).ToArray();
for (int j = 0; j< lAreaType.Count; j++)
{
DataRow dr = lDt.NewRow();
dr["AreaTypeID"] = lAreaType[j].LandmarkTypeID;
dr["CategoryRef"] = lAreaType[j].CategoryRef;
dr["Description"] = lAreaType[j].Description;
dr["CatDescription"] = lAreaType[j].;
lDt.Rows.Add(dr);
}
}
catch (Exception ex)
{
}
You can give them an explicit name when selecting:
select new { lt.AreaTypeID, LtDescr = lt.Description, lt.CategoryRef, CDescr = c.Description }
And then:
dr["Description"] = lAreaType[j].LtDescr;
dr["CatDescription"] = lAreaType[j].CDescr;
Change:
select new { lt.AreaTypeID, lt.Description, lt.CategoryRef, c.Description }
To:
select new { AreaTypeID = lt.AreaTypeID,
LtDescription = lt.Description,
CategoryRef = lt.CategoryRef,
CatDescription = c.Description }
That will give each property in the anonymous type a different explicit name rather than simply relying on the existing name. You can then access them later using:
dr["Description"] = lAreaType[j].LtDescription;
dr["CatDescription"] = lAreaType[j].CatDescription;

Resources