I have a class with two properties (name,family).
I have written code for insert into database without problems, but I don't know how to write the code to check if the data already exists?
I need sample for MVC 4 or higher.
Thanks in advance.
public ActionResult Create([Bind(Include="Name,Description")] ColorApplication colorapplication)
{
if (ModelState.IsValid)
{
db.ColorApplications.Add(colorapplication);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(colorapplication);
}
If you wanna use the DbSet, there are the Remove() or RemoveRange() options.
You can eighter remove one:
using (PersonContext db = new PersonContext())
{
Person person = db.Persons.Where(t => t.Name == "My Name").FirstOrDefault<Person>();
db.Persons.Remove(person);
db.SaveChanges();
}
Or give a list of entities that you want to remove:
using (PersonContext db = new PersonContext())
{
List<Person> persons = db.Persons.Where(t => t.Name == "My Name").ToList();
db.Persons.RemoveRange(persons);
db.SaveChanges();
}
You can also use raw SQL statements if you need something more specific:
DELETE FROM PERSON WHERE NAME = 'My Name'
Related
I have a working code here.
using (var db = new MyContextDB())
{
var result = db.Books.SingleOrDefault(b => b.BookNumber == bookNumber);
if (result != null)
{
result.MyColumnName= "Some new value";
db.SaveChanges();
}
}
But I have many properties to change. So I was trying for something like
result= newResult;
db.SaveChanges();
But this is not working. Is there any idea to replace a record with a new one?
I think, you can not do this so easily.
You should create a method in your Book class, where you change all of the properties.
result.Update(Book newProperties);
db.SaveChanges();
or
result.Update(string prop1, int prop2, etc.);
db.SaveChanges();
I would recommend to use Automapper. You can use it like this:
var result = db.Books.SingleOrDefault(b => b.BookNumber == bookNumber);
if (result != null)
{
Mapper.Map(newResult, result);
db.SaveChanges();
}
Notice, that probably you will need to properly configure Automapper(e.g. to ignore Id properties when updating)
I'm using asp.net c# with entity framework and i have tried to delete a record from database. So for that i have coded the controller part as below.
[HttpPost]
public ActionResult DeleteAccount(DeleteAccountViewModel deleteaccountviewmodel)
{
TheFoodyContext db = new TheFoodyContext();
string UserEmail = Session["UserEmail"].ToString();
User user_to_update = db.Users.SingleOrDefault(s => s.email == UserEmail);
if (user_to_update != null)
{
if ((deleteaccountviewmodel.Password == user_to_update.password))
{
db.Users.Remove(user_to_update);
db.SaveChanges();
return RedirectToAction("~/View/Home");
}
}
//return RedirectToAction("~/View/Home");
}
But in here it will give me an error because it doesn't identify 'Stores'. I don't know why is that. Can anyone help me?
your code seems to be correct. db.SaveChanges(); will return value you can check whether it is removed or not. but you are mentioned 'Stores' not identified means if you are trying to delete record from Stores table use db.Stores.Remove() if not explain clearly your problem
Am trying to create a cascading drop down and have been following this tutorial here
My database is more complex than the one in the tutorial and I need help with creating a lambda expression
Here are my database tables
The cascading drop down I want to create, will allow a user to select a
RiskType and then depending on the selection will display the associated GroupMembers for the selected RiskType.
Here is the code I have in my controller
public ActionResult AddNewRisk()
{
ViewBag.RiskTypeID = new SelectList(_DBContext.RiskTypes, "ID", "Description");
ViewBag.GroupMembers = new SelectList(new List<GroupMember>(), "ID", "Name");
return View();
}
public IList<GroupMember> GetGroupMember(int SelectedRiskTypeID)
{
return _DBContext
.RiskTypeHasGroups
}
public JsonResult GetJsonGroupMember(int ID)
{
var GroupMemberListT = this.GetGroupMember(Convert.ToInt32(ID));
var GroupMemberList = GroupMemberListT.Select(x => new SelectListItem()
{
Text = x.Name,
Value = x.ID.ToString()
});
return Json(GroupMemberList, JsonRequestBehavior.AllowGet);
}
It's in the method named GetGroupMember that am having trouble and don't know how to write the correct lambda expression in order to pull back only the group members which have a matching RiskGroup.ID followed by a matching RiskType.ID. If anyone could show me the correct way to do this, I'd really appreciate it.
Thanks in advance.
Once the model is simplified as I suggested, then your query becomes:
public IQueryable<GroupMember> GetGroupMember(int SelectedRiskTypeID)
{
return _DBContext.GroupMembers
.Where(g=>g.RiskGroups.Any(rg=>rg.ID=SelectedRiskTypeID));
}
If you decide to keep the IDs, then this would be your query:
public IQueryable<GroupMember> GetGroupMember(int SelectedRiskTypeID)
{
return _DBContext.GroupMembers
.Where(gm=>gm.RiskGroupHasGroupTypes
.Any(rghgt=>rghgt.RiskGroup.ID==SelectedRiskGroupTypeID))
}
i am trying to update a user table with a single value update, but i can't figure out what i'm doing wrong. this is what i have:
public static void ApplyROB(string ROBread, string userName)
{
using (SERTEntities ctx = CommonSERT.GetSERTContext())
{
// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=
// Audit of the transfer
datUser trUser = new datUserRole();
trUser.ROB = ROBread;
trUser.AccountName = userName;
// Persist update to DB
ctx.SaveChanges();
}
}
am i way off? nothing happens when i click on the update.
how do i say, where username = username? did i do it right?
basically in need a simple:
update datUser set ROB = "Y" where AccountName= "myusername"
it's turning out to be a bit more complicated in LINQ using Context
please help.
You're not adding your new entity to the context, thus when you save, the context is unaware of any changes. You need something like...
ctx.datUserRoles.Add(datUserRole)
To do an update, you need to retreive an entity from the context, make changes to it, then save... so:
var entity=ctx.datUserRoles.SingleOrDefault(dur=>dur.AccountName==someUserName);
if(entity!=null)
{
entity.someProp=someVal;
ctx.SaveChanges();
}
else
{
throw new UnexpectedOperationException(); //or however you want to fail
}
If you need an update. Maybe something like this:
public static void ApplyROB(string ROBread, string userName)
{
using (SERTEntities ctx = CommonSERT.GetSERTContext())
{
var trUser= ctx.datUserRole.Where(a=>a.AccountName==userName)
.FirstOrDefault();
if(trUser!=null)
{
trUser.ROB = ROBread;
ctx.SaveChanges();
}
}
}
If you are sure that you will always have something to update you can use First(). Then you do not need to check if the trUser is null
spender is correct in a sense, incorrect in another: you want to update an existing record.
For that you'll need to select the record first, for instance:
var user =
(from u in ctx.datUserRoles
where u.AccountName == "accountname"
select u).FirstOrDefault();
Where accountname is a valid thing of the same type - that doesn't matter, since you can select it how you want, you can touch that up to meet your criteria. Then once you have the item do the stuff:
if (user != null) {
user.ROB = ROBread;
ctx.SaveChanges();
}
Im want to delete rows from a table that in my data base.
i have the member
private static WeightScaleEntities Weight = new Weight();
this member contains my database. in the data base i have table: User_Activity.
I want to delete rows from user activity by given i_UserActivityId, as follow:
//Get the rows for delete
var deleteUserActivities = from details in Weight.User_Activity
where details.Id == i_UserActivityId
select details;
Now i want to delete this rows, so i tried to do:
foreach (var item in deleteUserActivities)
{
m_WeightScaleEntities.User_Activity.*
}
and i dont get the method DeleteOnSubmit!
Why?
there is another option???
User_Activity.*: is that a typo?
What I think you want is:
foreach (var item in deleteUserActivities)
{
Weight.DeleteObject(item);
}
And then SaveChanges() on the object context.
BTW, a static object context is not a good idea. You should carefully control the life cycle of object contexts.
There is more than one way to execute deletion in Entity Framework,
You must take into account what are the values that you want to delete? one Row or more.
when you need to delete on Row from table we can use these ways:
// first way
using (WeightScaleEntities db = new WeightScaleEntities())
{
var deleteUserActivities = from details in db.User_Activity
where details.Id == i_UserActivityId
select details;
if (deleteUserActivities.Count() > 0)
{
db.deleteUserActivities.Remove(deleteUserActivities.First());
db.SaveChanges();
}
}
this line deleteUserActivities.Count()>0 to check if you have result in the Query or not.
and this deleteUserActivities.First() if the query return set of rows delete the first. "to make the process more secure if you don't know about the data in the table"
// second way
using (WeightScaleEntities db = new WeightScaleEntities())
{
var deleteUserActivities = (from details in db.User_Activity
where details.Id == i_UserActivityId
select details).SingleOrDefault();
if (deleteUserActivities != null)
{
db.User_Activity.Remove(deleteUserActivities);
// or use this line
//db.Entry(deleteUserActivities).State = System.Data.Entity.EntityState.Deleted;
db.SaveChanges();
}
}
You can also use Single or SingleOrDefault to get a single object. Single or SingleOrDefault will throw an exception, if the result contains more than one element. Use Single or SingleOrDefault where you are sure that the result would contain only one element. If the result has multiple elements then there must be some problem.
Also, if you need to remove one or multi rows use this way:
using (WeightScaleEntities db = new WeightScaleEntities())
{
var deleteUserActivities = (from details in db.User_Activity
where details.Id == i_UserActivityId
select details).ToList<User_Activity>(); //<User_Activity> her name of your DbSet
foreach(deleteObject in deleteUserActivities)
{
db.Entry(deleteObject).State = System.Data.Entity.EntityState.Deleted;
}
db.SaveChanges();
}
Best Regards
and sorry about English language.
using(WeightScaleEntities db=new WeightScaleEntities())
{
var deleteUserActivities = from details in db.User_Activity
where details.Id == i_UserActivityId
select details;
if (deleteUserActivities.Count()>0)
{
db.deleteUserActivities.Remove(deleteUserActivities.First());
db.SaveChanges();
}
}