Need to access and edit an attribute in a database - c#

Orders are created and saved in this method
public async Task<ActionResult> FirstClassCreate(FormCollection values)
{
var order = new Order();
TryUpdateModel(order);
var customer = db.Users.FirstOrDefault(x => x.Email == User.Identity.Name);
var cart = ShoppingCart.GetCart(this.HttpContext);
try
{
order.DeliveryDate = DateTime.Now.AddDays(1);
order.DeliveryMethod = "First Class";
order.FirstName = customer.FirstName;
order.LastName = customer.LastName;
order.PostalCode = customer.PostalCode;
order.State = customer.State;
order.City = customer.City;
order.Email = customer.Email;
order.Country = customer.Country;
order.Phone = customer.PhoneNumber;
order.Address = customer.Address;
order.HasPaid = false;
order.Username = customer.Email;
order.OrderDate = DateTime.Now;
var currentUserId = User.Identity.GetUserId();
order.Total = cart.GetFirstClass();
if (order.SaveInfo && !order.Username.Equals("guest#guest.com"))
{
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
var ctx = store.Context;
var currentUser = manager.FindById(User.Identity.GetUserId());
//Save this back
//http://stackoverflow.com/questions/20444022/updating-user-data-asp-net-identity
//var result = await UserManager.UpdateAsync(currentUser);
await ctx.SaveChangesAsync();
await storeDB.SaveChangesAsync();
}
//Save Order
storeDB.Orders.Add(order);
await storeDB.SaveChangesAsync();
//Process the order
cart = ShoppingCart.GetCart(this.HttpContext);
order.Total = cart.GetFirstClass();
order = cart.CreateOrder(order);
return RedirectToAction("FirstClass", "Checkouts", order);
}
catch
{
//Invalid - redisplay with errors
return View(order);
}
}
I need to be access the orders database and change attributes of a specific order, using the email as the Unique Identifier and search for the newest (find the newest using the Order Date where 'haspaid' = false).
using ()//Insert database context here)
{
//Search for order in the database, try using the email as the Unique Identifire and search for the newest where haspaid = false
//Change the haspaid attribute to true
var orders = from o in db.Orders
where o.Email == User.Identity.Name, o.HasPaid = false, //Newest
select o;
order.HasPaid = true;
db.Orders.SaveChanges();
//save database changes
}

If I understand you correctly, you don't know how to query the record you want to update. So you need to use the Where() to filter the record and use the Max() function to get the latest date.
var orderToBeChanged = db.Orders
.Where(o => o.HasPaid == false && o => o.Email == User.Identity.Name)
.Max(o => o.OrderDate);

Related

Update a record using Entity Framework receiving 2 parameters

I want to update a specific row of the database. This is the code:
public void Update_Datos(int ID)
{
int UserId = Convert.ToInt16((string)(Session["UserId"]));
using (var db = new Entities())
{
//Reading
List<Datos_Personales> objDatos = db.Datos_Personales.ToList<Datos_Personales>();
foreach (Datos_Personales item in objDatos)
{
}
//Update
var datos_personales = db.Datos_Personales.FirstOrDefault(d => d.UserId == UserId && d.Id == ID);
Datos_Personales datos = objDatos[datos_personales.Id];
datos = db.Datos_Personales.Where(d => d.UserId == UserId && d.Id == ID).First();
datos.Fecha_de_nacimiento = Convert.ToDateTime(Fecha_de_nacimiento.Text);
datos.Nombre_Completo = txt_Nombre_Completo.Text;
datos.Identificacion = txt_Identificacion.Text;
datos.Estado_civil = ddEstadoCivil.SelectedValue;
datos.Telefono = txt_num_telefono.Text;
datos.Departamento = ddDepartamento.SelectedValue;
datos.Nacionalidad = Country.SelectedValue;
datos.Salario_min_aceptado = ddSalario_min_aceptado.SelectedValue;
datos.Titulo = txt_Titulo.Text;
datos.Descripcion_Profesional = txt_Descripcion_Profesional.Text;
datos.UserId = Convert.ToInt16(UserId);
db.Datos_Personales.Add(datos);
db.SaveChanges();
}
}
The other is issue is that it creating another row instead updating the one which I need.
You must not read all Db. When you use this line List<Datos_Personales> objDatos = db.Datos_Personales.ToList<Datos_Personales>();, your all entity (all rows in Db) stored into memory.
You can fetch your data directly and edit it. Finally you must not add entity again, only call SaveChages. (If you did not close ChangeTracker)
public void Update_Datos(int ID)
{
int UserId = Convert.ToInt16((string)(Session["UserId"]));
using (var db = new Entities())
{
Datos_Personales datos = db.Datos_Personales.FirstOrDefault(d => d.UserId == UserId && d.Id == ID));
if(datos == null)
return;
datos.Fecha_de_nacimiento = Convert.ToDateTime(Fecha_de_nacimiento.Text);
datos.Nombre_Completo = txt_Nombre_Completo.Text;
datos.Identificacion = txt_Identificacion.Text;
datos.Estado_civil = ddEstadoCivil.SelectedValue;
datos.Telefono = txt_num_telefono.Text;
datos.Departamento = ddDepartamento.SelectedValue;
datos.Nacionalidad = Country.SelectedValue;
datos.Salario_min_aceptado = ddSalario_min_aceptado.SelectedValue;
datos.Titulo = txt_Titulo.Text;
datos.Descripcion_Profesional = txt_Descripcion_Profesional.Text;
datos.UserId = Convert.ToInt16(UserId);
db.SaveChanges();
}
}

C# Get List Ids Inserted With SaveChangesAsync

I use net core to api controller and Client with React.
I want get details of list opportunity after insert to DB but I do not knowHow get list ids of data added?
My Code Insert Data.
var customers = await db.Customers.Where(c =>
c.Categories.Any(cate =>
model.CustomerCategories.Contains(cate.CategoryId)
)
).ToListAsync();
foreach(var customer in customers) {
if (String.IsNullOrEmpty(model.Name)) {
opportunityName = customer.FullName;
}
var opportunity = new Opportunity {
StepId = model.StepId,
Name = opportunityName,
Email = customer.Email,
Phone = customer.Phone,
CustomerId = customer.Id,
Status = IdentityStatus.Active,
ExpectedRevenue = model.ExpectedRevenue,
Probability = model.Probability,
Notes = model.Note,
Deadline = model.Deadline,
OwnerId = OwnerId,
Reason = model.Reason,
Revenue = model.Revenue,
CompleteDate = model.CompleteDate,
};
db.Opportunities.Add(opportunity);
}
await db.SaveChangesAsync();
Keep track of the entities you are adding, call SaveChangesAsync and then inspect them afterwards. EF will have populated their keys.
Here's some psuedo-code that should illustrate the idea:
var customers = await db.Customers.Where(c =>
c.Categories.Any(cate =>
model.CustomerCategories.Contains(cate.CategoryId)
)
).ToListAsync();
var opportunities = new List<Opportunity>(customers.Count);
foreach(var customer in customers) {
if (String.IsNullOrEmpty(model.Name)) {
opportunityName = customer.FullName;
}
var opportunity = new Opportunity {
StepId = model.StepId,
Name = opportunityName,
Email = customer.Email,
Phone = customer.Phone,
CustomerId = customer.Id,
Status = IdentityStatus.Active,
ExpectedRevenue = model.ExpectedRevenue,
Probability = model.Probability,
Notes = model.Note,
Deadline = model.Deadline,
OwnerId = OwnerId,
Reason = model.Reason,
Revenue = model.Revenue,
CompleteDate = model.CompleteDate,
};
opportunities.Add(opportunity);
//db.Opportunities.Add(opportunity);
}
db.Opportunities.AddRange(opportunities);
await db.SaveChangesAsync();
//foreach (var opportunity in opportunities)
// Console.WriteLine(opportunity.YourIdPropertyHere);

How to update a record using LINQ LAMBDA in my ASP.NET MVC 5 Project

I am new to entity framework and LINQ. I am stuck at an issue where I need to firstly check if the record already exists, if it exists then I need to update the record with column RESUMEID accordingly. If not then I need to add the record. I am able to add successfully but I don't know how to update the record in LINQ.
Below is my attempt:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ReferralViewModel viewModel)
{
var candidateId = User.Identity.GetUserId();
// I AM CONFUSED ABOUT BELOW STATEMENT
var IsDupeReferral = _context.Referrals
.Where(r => (r.CandidateId == candidateId)
&& (r.CompanyId == viewModel.CompanyId) && (r.SkillId == viewModel.SkillId))
.Select(r=>r.ReferralId).SingleOrDefault();
if(IsDupeReferral!=0)
{
//IF I FIND DUPE REFERRAL RECORD I WANT TO UPDATE SOME OF THE VALUES IN THAT
_context.Referrals.Where(r => r.ReferralId == IsDupeReferral).
AND UPDATE r.resumeId with viewModel.ResumeId // How to do this?
// NOT SURE ABOUT BELOW LINE EITHER
_context.SaveChanges();
}
else
{
// BELOW CODE IS WORKING FINE
var referral = new Referral
{
ReferralName = viewModel.ReferralName,
ResumeId = viewModel.ResumeId,
CandidateId = candidateId,
DegreeId = viewModel.DegreeId,
CoverLetterId = viewModel.CoverLetterId,
SkillId = viewModel.SkillId
};
if (!string.IsNullOrEmpty(viewModel.TempCompany))
{
var newCompany = new Company
{
CompanyName = viewModel.TempCompany
};
newCompany.Referrals.Add(referral);
_context.Companies.Add(newCompany); ;
}
else
{
referral.CompanyId = viewModel.CompanyId.Value;
_context.Referrals.Add(referral);
}
_context.SaveChanges();
}
return RedirectToAction("ReferralCenter");
}
Here's the solution
//IF I FIND DUPE REFERRAL RECORD I WANT TO UPDATE SOME OF THE VALUES IN THAT
var referral = _context.Referrals.FirstOrDefault(r => r.ReferralId == IsDupeReferral);
// AND UPDATE r.resumeId with viewModel.ResumeId
if (referral !=null) {
referral.resumeId = viewModel.ResumeId;
_context.Entry(referral).State = System.Data.EntityState.Modified;
_context.SaveChanges();
}
Actually, you don't need getting the IsDupeReferral and then request the record again. Try to combine your code as the following:
var referral = _context.Referrals
.Where(r => (r.CandidateId == candidateId)
&& (r.CompanyId == viewModel.CompanyId) && (r.SkillId == viewModel.SkillId)).SingleOrDefault();
if (referral !=null) {
referral.resumeId = viewModel.ResumeId;
_context.Entry(referral).State = System.Data.EntityState.Modified;
_context.SaveChanges();
}
else {
// add a new record
}
Referral referral = _context.Referrals.FirstOrDefault(r=> r.ReferralId = SomeId);
if(referral == null) // then referral does not exist - add it
{
referral = new Referral{
ReferralName = viewModel.ReferralName,
ResumeId = viewModel.ResumeId,
CandidateId = candidateId,
DegreeId = viewModel.DegreeId,
CoverLetterId = viewModel.CoverLetterId,
SkillId = viewModel.SkillId
};
_context.Referrals.Add(referral);
}
else // referral already exists - update its values
{
//make changes to referral
referral.ReferralName = viewModel.ReferralName;
referral.ResumeId = viewModel.ResumeId;
referral.CandidateId = candidateId;
referral.DegreeId = viewModel.DegreeId;
referral.CoverLetterId = viewModel.CoverLetterId;
referral.SkillId = viewModel.SkillId;
}
_context.SaveChanges(); //no matter added or updated - save the changes

Checking for existing records on database wen i call web api

I am calling a web api and saving the records on the database through the controller, i want each time im calling the api to check if the record exists in the database if yes then dont save, if not then save.
var client = new WebClient();
var text = client.DownloadString("https://www.test.com/api/all-users?name=testusername%20&pass=334432");
var wclients = JsonConvert.DeserializeObject<dynamic>(text);
List<apicli> list1 = new List<apicli>();
var clie = new apicli();
if (wclients.message == "success")
{
var data = wclients.data;
//var account = wclients.account;
ViewBag.test = data;
foreach(var item in ViewBag.test)
{
clie.Email = item.email;
clie.Name = item.name;
clie.Aff = item.affiliated_id;
foreach(var item1 in #item.account.real)
{
clie.Login = item1.login;
clie.password = item1.pass;
}
list1.Add(clie);
db.apiclis.AddRange(list1);
db.SaveChanges();
};
}
I would assume you need something like this, although you need to check what is the unique id of each record:
foreach(var item in data){
var c = new apicli {
Email = item.email,
Name = item.name,
Aff = item.affiliated_id
Login = item.account.real.LastOrDefault()?login??"",
Login = item.account.real.LastOrDefault()?pass??""
}
if(!db.apiclis.Any(a => a.Email == c.Email && a.Name == c.Name && a.Aff == c.Aff)){
db.apiclis.Add(c);
}
}
Here I assume that email+name+aff = unique identificator.

Search in IQueryable<T>

I am pulling some data from database by this line below:
IQueryable<user> UserList = DatabaseContext.Users.GetAll();
I want to seach something in UserList such as:
foreach (var User in UserList)
{
if (User.type == (int)UserType.SuperUser)
{
IsRecordFound = true;
break;
}
}
Then i do something according to the state of flag:
if (!IsRecordFound)
{
AesCrypto aesCrypto = new AesCrypto();
user newuser = new user();
newuser.username = DEFAULT_SUPER_USER_NAME;
newuser.password = aesCrypto.Encrypt(DEFAULT_SUPER_USER_PASSWORD);
newuser.type = (int)UserType.SuperUser;
newuser.create_date = DateTime.Now;
newuser.last_login = newuser.create_date;
newuser.email_address = DEFAULT_SUPER_USER_EMAIL_ADDR;
newuser.login_count = 1;
DatabaseContext.Users.Add(newuser);
if (!DatabaseContext.Save())
return false;
}
Is there any easy or practical way to seach in IQueryable interface by using LINQ or something else?
if (!UserList.Any(x => x.Type == (int)UserType.SuperUser))
{
AesCrypto aesCrypto = new AesCrypto();
user newuser = new user();
newuser.username = DEFAULT_SUPER_USER_NAME;
newuser.password = aesCrypto.Encrypt(DEFAULT_SUPER_USER_PASSWORD);
newuser.type = (int)UserType.SuperUser;
newuser.create_date = DateTime.Now;
newuser.last_login = newuser.create_date;
newuser.email_address = DEFAULT_SUPER_USER_EMAIL_ADDR;
newuser.login_count = 1;
DatabaseContext.Users.Add(newuser);
if (!DatabaseContext.Save())
return false;
}
You can do it like
bool isSuperUser = UserList.Any(a=>a.type==a.SuperUser)
to search an IQueryable, use where
var foundUsers = UserList.Where( usr => usr.Type == (int)UserTypes.SuperUser );
if( foundUsers == null && foundUsers.Count() == 0 ) // only one of these is required.. I forget which though :s
{
AesCrypto aesCrypto = new AesCrypto();
user newuser = new user();
newuser.username = DEFAULT_SUPER_USER_NAME;
newuser.password = aesCrypto.Encrypt(DEFAULT_SUPER_USER_PASSWORD);
newuser.type = (int)UserType.SuperUser;
newuser.create_date = DateTime.Now;
newuser.last_login = newuser.create_date;
newuser.email_address = DEFAULT_SUPER_USER_EMAIL_ADDR;
newuser.login_count = 1;
DatabaseContext.Users.Add(newuser);
if (!DatabaseContext.Save())
return false;
}
UserList .Where(user => user.Type== (int)UserType.SuperUser);

Categories

Resources