Having error in updating my record in database my method as follows - asp.net-mvc-4

What I have done wrong in this code ? (I am using MVC4 and EF)
As an example: Please clear this am fresher to use MVC4
EditResponse response = new EditResponse();
try
{
using (WeMatchContext db = new WeMatchContext())
{
B_MEMBER_REGISTER update = new B_MEMBER_REGISTER();
var output = db.B_MEMBER_REGISTER.Where(x => x.MEMBER_ID == model.MEMBER_ID).FirstOrDefault();
if(output != null )
{
update.FIRST_NAME = model.FIRST_NAME;
update.LAST_NAME = model.LAST_NAME;
update.GENDER = model.GENDER;
update.DOB = model.DOB;
int resultcount = db.SaveChanges();
if (resultcount > 0)
{
response.MEMBER_ID = update.MEMBER_ID;
response.ResultCode = 0;
response.Message = "Updated Successfully";
}

You have to attach updated data with the db entity. please try this,
using (WeMatchContext db = new WeMatchContext())
{
var update = db.B_MEMBER_REGISTER.Where(x => x.MEMBER_ID == model.MEMBER_ID).FirstOrDefault();
if(update != null )
{
update.FIRST_NAME = model.FIRST_NAME;
update.LAST_NAME = model.LAST_NAME;
update.GENDER = model.GENDER;
update.DOB = model.DOB;
//below line of code is very important.
db.B_MEMBER_REGISTER.Attach(update);
db.Entry(update).State = EntityState.Modified;
int resultcount = db.SaveChanges();
if (resultcount > 0)
{
response.MEMBER_ID = update.MEMBER_ID;
response.ResultCode = 0;
response.Message = "Updated Successfully";
}
}
}

Related

Convert EntityFramework to Raw SQL Queries in MVC

I am trying to make a crud calendar in my .net, my question is, How do make the below entity framework codes to SQL queries?
[HttpPost]
public JsonResult SaveEvent(Event e)
{
var status = false;
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
if (e.EventID > 0)
{
//Update the event
var v = dc.Events.Where(a => a.EventID == e.EventID).FirstOrDefault();
if (v != null)
{
v.Subject = e.Subject;
v.Start = e.Start;
v.End = e.End;
v.Description = e.Description;
v.IsFullDay = e.IsFullDay;
v.ThemeColor = e.ThemeColor;
}
}
else
{
dc.Events.Add(e);
}
dc.SaveChanges();
status = true;
}
return new JsonResult { Data = new { status = status } };
}
http://www.dotnetawesome.com/2017/07/curd-operation-on-fullcalendar-in-aspnet-mvc.html
Thanks guys
You can run raw query in entity framework with dc.Database.ExecuteSqlCommand() command like below:
var status = false;
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
if (e.EventID > 0)
{
dc.Database.ExecuteSqlCommand(&#"
UPDATE Events
SET Subject = {e.Subject},
Start = {e.Start},
End = {End},
Description = {Description},
IsFullDay = {IsFullDay},
ThemeColor = {ThemeColor},
WHERE EventID = {e.EventID}
IF ##ROWCOUNT = 0
INSERT INTO Events (EventID, Subject, Start, End, Description, IsFullDay, ThemeColor)
VALUES ({e.EventID}, {e.Subject}, ...)
");
status = true;
}
return new JsonResult { Data = new { status = status }
};

How to through error message in Yii2 Api?

Here is the code attached.
How can I throw an error message if any attribute is missing?
I need to check if all attributes are coming from the form or not. If any attribute is missing I want to throw an error message with proper error code.
$get_email = Null;
$get_password = Null;
$get_username = Null;
if (isset($_POST['username']) ) {
$get_username = $_POST['username'];
}
if (isset($_POST['email']) && isset($_POST['password']) ) {
$get_email = $_POST['email'];
$get_password = $_POST['password'];
}
if ($get_email == Null || $get_username == Null || $get_password == Null ) {
// through error code with message
}
else {
$model = new SignupForm();
$model->email = $get_email;
$model->username = $get_username;
$model->password = $get_password;
}
Here is the code through which I have achieved my goal.
$model = new SignupForm;
if (isset($_POST['username'] )) {
$model->username = $_POST['username'];
}
if (isset($_POST['email'] )) {
$model->email = $_POST['email'];
}
if (isset($_POST['password'] )) {
$model->password = $_POST['password'];
}
if($model->validate()){
$model->signup();
}
else{
return $model->getErrors();
}

Error: Only primitive types or enumeration types are supported in this context

[HttpPost]
public ActionResult Dep_Save_Attachments(int in_queue_id, HttpPostedFileBase httpfile, string authorized_by, string authorized_to, string confirmed_by, string approved_by)
{
if (httpfile != null)
{
var folder = Server.MapPath("~/Attachments/Laptops/" + in_queue_id + "/");
var prev_fa = db.File_Attachments.Where(x => x.inventory_table_id == in_queue_id).Where(x => x.is_active == true).ToList();
var prev_hfa = db.HW_Authorization_Forms.Where(x => x.file_attachments_id == prev_fa.FirstOrDefault().file_attachments_id).Where(x => x.is_active == true).ToList();
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
if (prev_fa.Count != 0)
{
foreach (var pf in prev_fa)
{
pf.is_active = false;
db.Entry(pf).State = EntityState.Modified;
db.SaveChanges(); ;
}
}
if (prev_hfa.Count != 0)
{
foreach (var hpf in prev_hfa)
{
hpf.is_active = false;
db.Entry(hpf).State = EntityState.Modified;
db.SaveChanges(); ;
}
}
try
{
string path = System.Web.HttpContext.Current.Server.MapPath("~/Attachments/Laptops/" + in_queue_id + "/") + System.IO.Path.GetFileName(httpfile.FileName);
httpfile.SaveAs(path);
File_Attachments fa = new File_Attachments();
fa.file_attachments_id = 1;
fa.inventory_table_name = "Laptops_Transactions";
fa.inventory_table_id = in_queue_id;
fa.file_name = System.IO.Path.GetFileName(httpfile.FileName);
fa.file_path = "http://" + Request.Url.Host + ":" + Request.Url.Port + "/Attachments/Laptops/" + httpfile.FileName;
fa.created_by = #User.Identity.Name.Remove(0, 9).ToLower();
fa.created_date = System.DateTime.Now;
fa.is_active = true;
db.File_Attachments.Add(fa);
db.SaveChanges();
Laptops_Transactions laptops_trans = db.Laptops_Transactions.Find(in_queue_id);
laptops_trans.lp_trans_type = "deployed";
laptops_trans.lp_date_returned = System.DateTime.Now;
db.Entry(laptops_trans).State = EntityState.Modified;
db.SaveChanges();
HW_Authorization_Forms hwf = new HW_Authorization_Forms();
hwf.hw_authorization_forms_id = 1;
hwf.file_attachments_id = fa.file_attachments_id;
hwf.hw_authorized_by = authorized_by;
hwf.hw_authorized_to = authorized_to;
hwf.hw_confirmed_by = confirmed_by;
hwf.hw_approved_by = approved_by;
hwf.hw_approved_date = fa.created_date;
hwf.created_by = fa.created_by;
hwf.created_date = fa.created_date;
hwf.hw_authorized_date = fa.created_date;
hwf.hw_confirmed_date = fa.created_date;
hwf.is_active = true;
db.HW_Authorization_Forms.Add(hwf);
db.SaveChanges();
}
catch
{
}
}
else
{
return Content("<script language='javascript' type='text/javascript'>alert('Please Attach the Deployment Authorization Form! Kindly go back to previous page');</script>");
}
return RedirectToAction("Index");
}
The error is on this line:
var prev_hfa = db.HW_Authorization_Forms.Where(x => x.file_attachments_id == prev_fa.FirstOrDefault().file_attachments_id).Where(x => x.is_active == true).ToList();
This is my code in the controller, actually this is working already but it suddenly have a error. I really don't have an idea why i have this kind of error where before it works perfectly.
Please help me with this. Need some advice. Thanks in advance.
The error is because of Datatype issue i guess, you need to confirm you are doing with correct datatype, file_attachments_id of database and from your comparing value must be same.
Also, is_active must be of datatype Boolean. Correcting this may solve your error.

Nhibernate Throws Found shared references to a collection

I have read thru a number of other questions similar to this one - but being new to Nhibernate, none of them seem to answer my question of why is Inhibernate throwing a "Found shared references to a collection: Order.ShippingAddress.Items" to the following code:
VendorOrderNotificationAcknowledgement ICheckoutVendorService.SendOrderNotification(VendorOrderNotification request)
{
OrderRepository repo = new OrderRepository();
var order =(AbstractOrder) repo.FindByCartId(request.OrderNotification.CartOrderId);
ShippingAddress billingAddress = order.ShippingAddresses[0];
var itemsFromDb = billingAddress.Items;
order.ClearAllShippingAddresses();
wcfFactory.UpdateOrder(order); //NO ERROR THROWN HERE!
ShippingAddress shippingAddress = orderHelper.CreateShippingAddress(request.ShippingDetails);
shippingAddress.Items = itemsFromDb;
order.AddShippingAddress(shippingAddress);
order.SourceCode = _sourceCode;
order.TaxAmount = 0;
order.GiftCertificateAmount = 0;
order.Status = StatusCode.Approved;
order.CreatedAt = request.OrderNotification.OrderTime.Year >2010
? request.OrderNotification.OrderTime
: DateTime.Now;
order.PurchasedDate=
request.OrderNotification.OrderTime.Year>2010
? request.OrderNotification.OrderTime
: DateTime.Now;
order.UpdatedAt = DateTime.Now;
if (request.OrderNotification.OrderCharges != null)
{
order.ShippingAmount = request.OrderNotification.OrderCharges.Shipping;
order.TaxAmount = request.OrderNotification.OrderCharges.DutyAndTaxes;
}
else
{
order.ShippingAmount = 0;
order.TaxAmount = 0;
}
order.UseGiftWrap = false;
order.SourceCode = _sourceCode;
UpdateEshopWorldOrder(order); // THROWS FOUND SHARED REFERENCES TO A COLLECTION: ORDER.SHIPPINGADDRESS.ITEMS
var orderDto = orderHelper.CreateOrderDto(billingAddress, orderHelper, order);
var dtoShippingAddresses = orderHelper.CreateDtoShippingAddresses(order);
orderDto.ShippingAddresses = dtoShippingAddresses;
ShippingMethodDto shippingMethodDto = 0;
var mine = wcfFactory.SendOrder(orderDto);
//More Code below here ...
}
public OrderDto CreateOrderDto(ShippingAddress billingAddress, OrderHelper orderHelper, AbstractOrder order)
{
OrderDto orderDto = new OrderDto();
orderDto.AlternateOrderId = order.Id.ToString();
orderDto.ConfirmationNumber = order.ConfirmationNumber;
orderDto.Coupons = new string[0];
orderDto.DiscountAmount = order.DiscountAmount;
orderDto.GiftCardAmount = order.GiftCertificateAmount;
orderDto.PurchaseDate = order.PurchasedDate;
orderDto.ShippingAmount = order.ShippingAmount;
orderDto.SourceCode = order.SourceCode;
orderDto.TaxAmount = order.TaxAmount;
orderDto.UseGiftWrap = order.UseGiftWrap;
var customerDto = orderHelper.CreateCustomerDto(billingAddress);
orderDto.SoldTo = customerDto;
return orderDto;
}
public void UpdateEshopWorldOrder(AbstractOrder order)
{
try
{
//Session.Update(order);
// transaction.Commit();
Session.Flush();
}
catch (Exception ex)
{
_logger.Debug("order saved failed with an error of " + ex.Message);
_logger.Error(ex);
throw;
}
}
Any insights are appreciated....
thnx
I think the problem is, that your itemsFromDB collection object is referenced by shippingAddress and also by billingAddress.
Both entities need their own collection-objects. Both collections however may contain references to the same address-objects.
So I assume replacing shippingAddress.Items = itemsFromDb; with something like
shippingAddress.Items.AddRange(itemsFromDb)
or
shippingAddress.Items = new List<ShippingAddress>(itemsFromDb) should do the trick

Why does this controller double the inserts when I try to archive the results of the Bing Search API?

I'm trying to archive my search results for a term by
Using the Bing API in an async controller
Inserting them into database using Entity Framework
using the Bing API and insert them into a database using entity framework. For whatever reason it is returning 50 results, but then it enters 100 results into the database.
My Controller Code:
public class DHWebServicesController : AsyncController
{
//
// GET: /WebService/
private DHContext context = new DHContext();
[HttpPost]
public void RunReportSetAsync(int id)
{
int iTotalCount = 1;
AsyncManager.OutstandingOperations.Increment(iTotalCount);
if (!context.DHSearchResults.Any(xx => xx.CityMarketComboRunID == id))
{
string strBingSearchUri = #ConfigurationManager.AppSettings["BingSearchURI"];
string strBingAccountKey = #ConfigurationManager.AppSettings["BingAccountKey"];
string strBingUserAccountKey = #ConfigurationManager.AppSettings["BingUserAccountKey"];
CityMarketComboRun cityMarketComboRun = context.CityMarketComboRuns.Include(xx => xx.CityMarketCombo).Include(xx => xx.CityMarketCombo.City).First(xx => xx.CityMarketComboRunID == id);
var bingContainer = new Bing.BingSearchContainer(new Uri(strBingSearchUri));
bingContainer.Credentials = new NetworkCredential(strBingUserAccountKey, strBingAccountKey);
// now we can build the query
Keyword keyword = context.Keywords.First();
var bingWebQuery = bingContainer.Web(keyword.Name, "en-US", "Moderate", cityMarketComboRun.CityMarketCombo.City.Latitude, cityMarketComboRun.CityMarketCombo.City.Longitude, null, null, null);
var bingWebResults = bingWebQuery.Execute();
context.Configuration.AutoDetectChangesEnabled = false;
int i = 1;
DHSearchResult dhSearchResult = new DHSearchResult();
List<DHSearchResult> lst = new List<DHSearchResult>();
var webResults = bingWebResults.ToList();
foreach (var result in webResults)
{
dhSearchResult = new DHSearchResult();
dhSearchResult.BingID = result.ID;
dhSearchResult.CityMarketComboRunID = id;
dhSearchResult.Description = result.Description;
dhSearchResult.DisplayUrl = result.DisplayUrl;
dhSearchResult.KeywordID = keyword.KeywordID;
dhSearchResult.Created = DateTime.Now;
dhSearchResult.Modified = DateTime.Now;
dhSearchResult.Title = result.Title;
dhSearchResult.Url = result.Url;
dhSearchResult.Ordinal = i;
lst.Add(dhSearchResult);
i++;
}
foreach (DHSearchResult c in lst)
{
context.DHSearchResults.Add(c);
context.SaveChanges();
}
AsyncManager.Parameters["message"] = "The total number of results was "+lst.Count+". And there are " + context.DHSearchResults.Count().ToString();
}
else
{
AsyncManager.Parameters["message"] = "You have already run this report";
}
AsyncManager.OutstandingOperations.Decrement(iTotalCount);
}
public string RunReportSetCompleted(string message)
{
string str = message;
return str;
}
}
Here is how I am calling it from my asp.net mvc 4 page.
#Ajax.ActionLink("Run Report", "GatherKeywordsFromBing", "DHWebServices",
new { id=item.CityMarketComboRunID},
new AjaxOptions { OnSuccess = "ShowNotifier();", UpdateTargetId = "TopNotifierMessage", HttpMethod = "POST", InsertionMode = InsertionMode.Replace, LoadingElementId = strCityMarketComboProgressID, LoadingElementDuration = 1000 },
new { #class = "ViewLink" })
<span class="ProgressIndicator" id="#strCityMarketComboProgressID"><img src="#Url.Content("~/Content/img/SmallBall.gif")" alt="loading" /></span>
For whatever reason all of
Try saving only once:
foreach (DHSearchResult c in lst)
{
context.DHSearchResults.Add(c);
}
context.SaveChanges();
Also there's nothing asynchronous in your code, so there's no point of using asynchronous controller. Not only that it won't improve anything but it might make things worse.