Can't update an entity with Poco Code Generation Item - c#

I have the following scenario:
the below 2 global variables in my page:
MainContext db = new MainContext();
User user = new User();
A method to fill the properties that is called on the button update:
private void FillProperties()
{
user.FirstName = txtFirstName.Text;
user.LastName = txtLastName.Text;
user.Email = txtEmail.Text;
}
on the button update i am doing the following:
FillProperties();
user.ID = Request.QueryString("userid");
db.SaveChanges();
but the record isn't been updated which i think is logical since the user variable isn't related to db object, but i a, not being able to do this:
db.Users.AddObject(user);
since AddObject isn't found in the db properties.
What can I do to update user?
Your answers are appreciated.

If you are using the DbContext API simply use
db.Entry(user).State = EntityState.Modified;

Where do you add your user to the DB?
If the user exists in the DB, in order to update it, you should do, for example:
user = db.Users.Where(x => x.ID == Request.QueryString("userid")).Single();
FillProperties();
db.SaveChanges();

Related

Inserting a row into Relational database table

I am very new to c# and asp.net mvc. I'm building a HR portal for our company where a user can submit a leave form among other things... So I'm using mssql as the database server and using Entity Frame work to communicate with it. I have 3 entities, user (Containing user details), permissions (the user permissions for allowing actions in the app) and then the leave form table (where the leave form details are stored). There is a one to many relationship between user - permission and then a one to many relationship between user-leave. I am not fazed about the permissions as that gets created when the user account is being created.
The problem I am facing is, how do I add a leave form for a specific user? Below is my controller code:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Leave(MasterViewModel model)
{
DocSubViewModel mv = model.DSModel;
int userId = Convert.ToInt32(Session["userID"]);
try
{
using (HrDcpDBContainer db = new HrDcpDBContainer())
{
var leave = db.leaves.Create();
leave.dateFrom = mv.DateFrom;
leave.dateSubmitted = DateTime.Now;
leave.dateTo = mv.DateTo;
leave.nrDays = mv.NrDays;
leave.reason = mv.SpecialLeave;
leave.TLApproval = null;
leave.TLApprovalDate = null;
leave.TLApprovalID = mv.TeamLeaderID;
leave.DMApprovalDate = null;
leave.DMApprovalID = mv.DepManagerID;
leave.DMApproval = null;
leave.type = mv.Type;
leave.user = userId;
db.leaves.Add(leave);
db.SaveChanges();
}
ViewBag.Message = "Leave Form submitted Successfully. You will be redirected shortly...";
return View("result");
}
catch (Exception ex)
{
ViewBag.Message = ex;
//ViewBag.Message = "Leave Form submitted Successfully. You will be redirected shortly...";
return View("result");
}
The problem comes in leave.user = userId;. It says:
Cannot implicitly convert int to Portal.Model.user
I can't seem to find out how to do this...
You're telling it to put the UserId where your leave model is asking for a User.
Your relationship requires a User to go in there, so you'll have to update your code a little bit:
using (HrDcpDBContainer db = new HrDcpDBContainer())
{
var leave = db.leaves.Create();
leave.user = db.users.First(x => x.Id == userId);
}
This will put reference to the actual user in the new leave record. If you go later and check it out you'll see a column in the leave table called user_Id that has an integer value in it and is set as a foreign key to the users table.
Note that this will error if no user exists having the specified Id value. If you anticipate this to be a problem, rather use .FirstOrDefault() instead of .First() and then account for the value being null before you add it to your new leave object.
That's expected since User is a object and not int. What you should be doing probably is leave.user.UserId = userId; instead [Assuming leave.user is of type User which has a UserId property]

CreateUserAndAccount and db.SaveChanges causes duplicate user entry

I am working on a ASP.NET MVC 4 web application. The following code causes that the user will be created two times in the UserProfile Table.
...
WebSecurity.CreateUserAndAccount(UserName, Password);
var UserProfile = (from UserProf in _db.Users
where UserProf.UserName == UserName
select UserProf).FirstOrDefault();
UserCustomAttribute = new UserCustomAttribute();
UserCustomAttribute.UserProfile = UserProfile;
UserCustomAttribute.Name = "BelongsToAccountId";
UserCustomAttribute.Value = model.AgentModel.AccountId;
using (db = new xDb())
{
db.UserCustomAttributes.Add(UserCustomAttribute);
db.SaveChanges();
}
...
Using VS2012 debugging feature, I discovered that one entry is created when calling
WebSecurity.CreateUserAndAccount(UserName, Password);
And, the duplicate is created when calling
db.SaveChanges();
This is weird. I would expect that SaveChanges() is called in CreateUserAndAccount(...)?!
So, how to add something to database without duplicating created user?

EF 4 does not update database record on db.SaveChanges()

Hi I have this code snippet below:
Paypal paypal = new Paypal();
paypal.Invoice = transactionID;
paypal.TxnType = "";
paypal.CreateDate = DateTime.Now;
paypal.AmountPaid = payment;
paypal.PaymentStatusId = paymentStatus;
db.Paypals.Add(paypal);
db.SaveChanges();
// Order Does not Update
Order order = _orderRepository.GetOrderByOrderId(orderId);
order.OrderStatusId = OrderStatusConstant.Paid;
order.PurchasedDate = DateTime.Now;
order.LastModified = DateTime.Now;
order.PaypalIpnId = paypal.PaypalIpnId;
db.SaveChanges();
// Cart Does not Update
Cart cart = _cartRepository.GetCartByCartId(order.CartId);
cart.Completed = true;
db.SaveChanges();
Order and Cart entity does not update. But Paypal object is inserted. There are no errors or any exceptions thrown this is enclosed in a try..catch clause.
What seems to be the problem here? Repository codes returns object fine.
I see one thing in common here for Order and Cart and different for Paypal. Paypal is inserted using the context that is shown in the code, but Cart and Order are downloaded from the repository. Make sure that repository is using the same context.
So... when Insert work but Update doesn't, I look at the AutoDetectChange property (in context.Configuration).
If you don't want this tracking (mean AutoDetectChange = false), you have to set manually your modified entities as modified (EntityState).
(the insert works because the Add method modifies the object's entityState)

linq to sql one-one relationship C#

It is necessary that after the creation of records in the table "Clients" took up ID. Later ID used to create a new entry in the "Clients_details".
var user = GetUsers();
var userdet = GetclientsDetails();
string hashedpass = getMd5Hash(UIPassword.Text);
var newreg = new Clients
{
login = UILogin.Text,
password = hashedpass,
subscribeid = Convert.ToInt32(UIId.Text)
};
user.InsertOnSubmit(newreg);
user.Context.SubmitChanges();
var details = new Clients_details
{
city = UICity.Text,
first_name = UIFirst_name.Text,
last_name = UIFamiliya.Text,
name = UIName.Text,
Clients = newreg
};
userdet.InsertOnSubmit(details);
userdet.Context.SubmitChanges();
After this code fails:
"An attempt was made to perform an operation Attach or Add in relation to an object that is not new, and possibly loaded from another DataContext. This operation is not supported."
How to properly create a record that does not appear a mistake? Thank you!
private static Table<Clients> GetUsers()
{
var dce = new BaseDBMLDataContext();
return dce.Clients;
}
private static Table<Clients_details> GetclientsDetails()
{
var dce = new BaseDBMLDataContext();
return dce.Clients_details;
}
Looks like userdet.Context and user.Context was built using a different dataContext and that needs to be created using the same dataContext rather than instantiating a new one.
I think you need to only call the SubmitChanges only once in the end, and also you need to make sure the user and userdet you are using share the same context
As the error clearly states, you're using different contexts (user and userdet) for each entity to add. You should have one DataContext and use that one to add the entities.
Yes looks like you're using two different instances of the same context:
user.Context.SubmitChanges();
userdet.Context.SubmitChanges();
A good approach to build up your entities should be something like :
//Create your client details entity
var details = new Clients_details
{
city = UICity.Text,
first_name = UIFirst_name.Text,
last_name = UIFamiliya.Text,
name = UIName.Text
};
//Create your client entity
var newreg = new Clients
{
login = UILogin.Text,
password = hashedpass,
subscribeid = Convert.ToInt32(UIId.Text),
//Assigning the details entity (FK) to the client
ClientDetails = details
};
//Saving both the client and its details
user.InsertOnSubmit(newreg);
user.Context.SubmitChanges();

how to skip object when submitchanges in ado.net

I'm using ado.net entity data model. I have 2 object User Organization
My problem is
User user=new User();
...
Organization org=new Organization()
db.Organizations.AddObject(org);
db.SubmitChanges(); // Problem is here. Because datacontext try to save user object. user object some field is empty. I don't need to save user here. How to skip user object from submitchanges
user.organization=org;
db.SubmitChanges(); // I need to save user object here
You need a using statement to scope out your data context.
Not exactly sure what you are trying to achieve, but something like this?
Organization org=new Organization();
User user = new User();
using (var ctx = new YourContext())
{
ctx.Organizations.InsertOnSubmit(org);
ctx.SubmitChanges();
user.Organization = org;
}
using (var newCtx = new YourContext())
{
// code to persist user
}

Categories