asp.net How to insert record into database - c#

I am having difficulties on getting my insert method to work correctly. I am new to back end development so any suggestions or comments will be helpful.
public Boolean insertDefaultUser()
{
Boolean flag = true;
Users newUser = new Users();
newUser.alias = "bulby";
newUser.password = "chicken";
newUser.email = "r#hot.com";
dbc.Users.AddObject(newUser); // ERROR !
dbc.SaveChanges();
return flag;
}
However, on the "add object line" it gives me the follow error --->
Error "The best overloaded method match for System.Data.Objects.ObjectSet<Guild_Chat.User>.AddObject(Guild_Chat.User)' has some invalid arguments ".

Try adding the actual entity type Guild_Chat.User, for example:
public bool InsertDefaultUser()
{
try
{
Guild_Chat.User newUser = new Guild_Chat.User
{
alias = "bulby",
password = "chicken",
email = "r#hot.com"
};
dbc.Users.AddObject(newUser);
dbc.SaveChanges();
return true;
}
catch(Exception e)
{
return false;
}
}

Related

How to fix 'Nullable object must have a value' for a string using TempData

I am checking to see if a user has payment data associated with them and to display that data if so.
I've tried redefining 'paymentMessage' in various ways to no avail. I am getting the error that paymentMessage must have a value.
public ActionResult Index() {
string paymentMessage = (string)TempData["payment_result"];
PublicBasicDetailsViewModel viewModel = new PublicBasicDetailsViewModel();
viewModel.Patron = Datasource.GetPatron(CurrentUser.PatronId.Value);
viewModel.Transactions = Datasource.GetPatronTransactionList(viewModel.Patron.PatronID);
viewModel.IsFirstLogin = CurrentUser.IsFirstLogin;
if (CurrentUser.IsFirstLogin) {
string userIdent = HttpContext.User.Identity.GetUserId();
Datasource.SetFirstLogin(userIdent);
}
if (paymentMessage == null) {
viewModel.HasPaymentResult = false;
return View(viewModel);
}
else if (paymentMessage == "SUCCESS") {
viewModel.HasPaymentResult = true;
return View(viewModel);
}
else {
viewModel.HasPaymentResult = true;
viewModel.Errors = paymentMessage;
return View(viewModel);
}
}
This is the error message appearing when I log in as a user
Exception Details: System.InvalidOperationException: Nullable object
must have a value.
Source Error: Line 57: string paymentMessage =
(string)TempData["payment_result"];
Tempdata has a lifetime of two actions.
https://www.codeproject.com/Tips/827059/Data-Passing-Mechanism-in-MVC-Architecture

Can't save record using Entity Framework

My objects will not save no matter what I do they will fetch and get info and make a new record but not update.
This is the code that details with getting existing patient and then modifying the record setting the state then calling save change this is cracking my head the last three hours what is going wrong. I was told you had to change the entity state of an object before it would no if to save but when i try to attach it it says its already attached
Appointment _appointment = new Appointment();
int errorCount = 0;
Patient _patient = SourceDal.getPatientByPatientNewId(Convert.ToInt32(txtPatientId.Text));
_patient.SSN = txtSSN.Text;
_patient.FirstName = txtPatientFirstName.Text;
_patient.LastName = txtPatientLastName.Text;
_patient.Middle = txtPatientMiddle.Text;
_patient.AddressOne = txtPatientAddressOne.Text;
_patient.City = txtPatientCity.Text;
_patient.State = txtPatientState.Text;
_patient.ZipCode = txtPatientZip.Text;
_patient.HomePhone = txtPatientHomePhone.Text;
_patient.WorkPhone = txtPatientWorkPhone.Text;
_patient.CellPhone = txtPatientCellPhone.Text;
if (rBtnHomePhone.Checked == true)
// _patient.ApptPhone = txtPatientHomePhone.Text;
if (rBtnHomePhone.Checked == true)
// _patient.ApptPhone = txtPatientHomePhone.Text;
if (rBtnWorkPhone.Checked == true)
// _patient.ApptPhone = txtPatientWorkPhone.Text;
_patient.BirthDate = dtBirthDate.DateTime;
_patient.emailAddress = txtPatientEmail.Text;
_patient.Race = Convert.ToInt32(dpRace.SelectedValue);
_patient.Ethnicity =Convert.ToInt32(dpEthnicity.SelectedValue);
_patient.Language = Convert.ToInt32(dpLanguages.SelectedValue);
if (dpGender.Text == "")
{
dpGender.Focus();
errorCount = 1;
lblGenderRequired.Text = "* Gender is required.";
}
else
{
errorCount = 0;
lblGenderRequired.Visible = false;
}
_patient.Gender = "M";
_patient.PatientID = txtPatientId.Text;
SourceDal.SourceEntities.Patients.Attach(_patient);
SourceDal.SourceEntities.Patients.Context.ObjectStateManager.ChangeObjectState(_patient, EntityState.Modified);
SourceDal.SourceEntities.SaveChanges();
The error I get is
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.Entity.dll
Additional information: An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
Edit 2:
Code to show my function getPaitnetByPatineyNewId
public Patient getPatientByPatientNewId(int newId)
{
Patient patient = new Patient();
if (newId == -1)
{
patient = new Patient();
}
else
{
patient = SourceEntities.Patients
.Where(w => w.ID == newId)
.FirstOrDefault();
}
return patient;
}
I think you have some issues with proper separation of concerns within your DAL, but for the short solution, you should only add (and not attach) if it's a new entity
if (_patent.PatentId == 0)
{
_patient.PatientID = txtPatientId.Text; // If you're using an identity column, remove this line. I would also strongly suggest not letting the user change this...
SourceDal.SourceEntities.Patients.Add(_patient);
}
For Anyone else the above scenarios did not work for me so this is what I had to do. I put a flag on my forms isUpdate and check that on the save button then if save call similar to below then if add just call savechanges and its now working thank you for everyone help hope this help someone.
public void SaveProviders(Provider _providers)
{
try
{
using (var ctx = new SMBASchedulerEntities(this.Connectionstring))
{
ctx.Providers.Add(_providers);
ctx.Entry(_providers).State = System.Data.Entity.EntityState.Modified;
ctx.SaveChanges();
}
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
}

Variable always returning true

I have this in my button click event:
protected void btn_login_Click(object sender, EventArgs e)
{
authentication auth = new authentication();
bool emailExists = auth.checkEmail(System.Convert.ToString(txt_email.Text));
if (emailExists == true)
{
btn_create.Text = "Email doesnt exist";
}
else
{
btn_create.Text = "Email exists";
}
}
It sends the email to my checkEmail method which is in my authentication class:
public bool checkEmail(string email)
{
bool emailExists = false;
usersTableAdapters.UsersTableAdapter user = new usersTableAdapters.UsersTableAdapter();
users.UsersDataTable userDataTable = user.checkEmail(email);
if (userDataTable.Rows.Count == 0)
{
emailExists = false;
}
else
{
emailExists = true;
}
return emailExists;
}
The checkEmail query is "SELECT COUNT(email) AS email FROM People WHERE (email = ?)"
However when I debug, it always falls through the if(emailExists == true) statement even when the email already exists in my DB, does anyone know why?
your query you entered will always have 1 result. If you want to continue using that query, you should check the first column ("email") of the first result and check to see if that is == 0 or not.
can't add code markup in comments, so reposting how I would rewrite the checkEmail method: (assuming the how the UsersTableAdapter type is setup)
public bool checkEmail(string email)
{
usersTableAdapters.UsersTableAdapter user = new usersTableAdapters.UsersTableAdapter();
users.UsersDataTable userDataTable = user.checkEmail(email);
return userDataTable.Rows[0][0] > 0;
}
I figured out I would have to check the index of the row which in this case is 0 and then retrieve and store the value from the email column into an int
DataRow row = userDataTable.Rows[0];
int rowValue = System.Convert.ToInt16(row["email"]);

IF-IF-Else doesn't work as I need and want

I need to know how I could handle my problem in a efficient and smart way:
I want an error-handling for user's input; I have 2 fields CustomerID and Company:
if (customerIDExists)
{
errorMessage = "...";
}
if (companyInvalid)
{
errorMessage = "...";
}
else
{
// Add user to DB
}
There could be 3 errors:
CustomerID already exists
Company has an invalid name
CustomerID AND Company is invalid at the same time
With the example above the else is for the last if (companyInvalid). How can I deal with the else that this only executes when the 1 and 2 if doesn't match?
Else if is not right because I have to check all opportunities.
Well, you could make it very explicit:
if (customerIDExists)
{
...
}
if (companyInvalid)
{
...
}
if (!customerIDExists && !companyInvalid)
{
// Add user to DB
}
Or just use the fact that you haven't got an error message:
string errorMessage = null;
if (customerIDExists)
{
errorMessage = ...;
}
if (companyInvalid)
{
errorMessage = ...; // Don't forget it could already be non-null!
}
if (errorMessage == null)
{
// No error message, so we must be fine
// Add user to DB
}
If I understand your problem the else will fire if customerIDExists is true.
Try this
if(customerIDExists)
{
errorMessage = "...";
}
else if(companyInvalid)
{
errorMessage = "...";
}
else
{
// Add user to DB
}
I've added an else if to the second condition. Now your application will check if the customerIDExists, if it doesn't it will check if the companyInvalid if it doesn't it will add the user to the database.
Now, what happens if both of these are incorrect? You'll only present on error message to your user, this will be annoying when they fix that issue and discover they have another you didn't tell them about! My suggestion would be to use a list of errors, if there aren't any then save to the database:
var errors = new List<string>();
if(customerIDExists)
{
errors.Add("Customer exists");
}
if(companyInvalid)
{
errors.Add("Company invalid");
}
if(!errors.Any())
{
// Add user to DB
}
return errors;
You can use a variable:
bool isValid = true;
if(customerIDExists)
{
errorMessage = "...";
isValid = false;
}
if(companyInvalid)
{
errorMessage = "...";
isValid = false;
}
if(isValid)
{
// Add user to DB
}
You can try old technique:
do {
if(customerIDExists)
{
errorMessage = "...";
break;
}
if(companyInvalid)
{
errorMessage = "...";
break;
}
// All is ok.
} while (false);
If you want to show all messages and don't break the proof after first error, you could use something like this:
List<string> errorMessages = new List<string>();
if (customerIDExists)
{
errorMessages.Add("...");
}
if (companyInvalid)
{
errorMessages.Add("...");
}
if (errorMessages.Count == 0) //Valid
{
}
else //Invalid
{
}
I assume you'd want to report all errors, not just the first that's encountered.
var errors = new List<string>();
if (customerIDExists)
{
errors.Add("customer id exists");
}
if (companyInvalid)
{
errors.Add("company is invalid");
}
if(errors.Any())
{
// display all error messages
}
else
{
// Add user to DB
}

Error adding multiple records MVC

i'm trying to add multiple textbox values to database it is working on just single textbox row but now working when i'm adding multiple rows of textboxes. i'm sharing what i have done so far.
Action Method:
public async Task<ActionResult> Create(FormCollection values)
{
var customer = new Customer();
var model = new TicketViewModel();
TryUpdateModel(model.TicketDetail);
try
{
foreach (var ticket in model.Tickets)
{
ticket.Date = DateTime.Now;
ticket.ProcessId = DateTime.Now.Ticks.ToString().Substring(12, 6);
ticket.CreationMethod = "Manual";
ticket.isCustomer = User.IsInRole("Customer") ? true : false;
ticket.Total = 0;
ticket.Email = model.TicketDetail.Ticket.Email;
customer.City = "Not Specified";
customer.Country = "Not SPecified";
customer.Image = "~/Images/nopic.jpg";
customer.Password = System.Web.Security.Membership.GeneratePassword(11, 3);
customer.IsActive = true;
customer.CreationMethod = "Manual";
customer.DateAdded = DateTime.Now;
customer.Email = ticket.Email;
customer.FirstMidName = string.IsNullOrEmpty(ticket.FullName) ? "Not Specified" : ticket.FullName;
customer.LastName = "Not Specified";
customer.Salutation = "Not Specified";
customer.UserName = DateTime.Now.Ticks.ToString().Substring(3, 9);
//ticket detail
var abcd = values["abcd"].ToString();
var getID = await db.Parts.Where(c => c.PartNumber == abcd)
.FirstOrDefaultAsync();
model.TicketDetail.GenericOrderId = ticket.GenericOrderId;
model.TicketDetail.PersonID = customer.PersonID;
model.TicketDetail.Status = "New";
model.TicketDetail.PartId = getID.PartId;
model.TicketDetail.Ticket.Date = DateTime.Now;
}
try
{
// db.Tickets.Add(ticket);
db.Customers.Add(customer);
db.TicketDetails.Add(model.TicketDetail);
}
catch (Exception ex)
{
ViewBag.PartId = new SelectList(db.Parts.Take(5), "PartId", "Name");
ModelState.AddModelError("", string.Format(ex.Message + "\n" + ex.InnerException));
return View(model.TicketDetail);
}
// Save all changes
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
catch(Exception ex)
{
ModelState.AddModelError("", String.Format(ex.Message + "\n" + ex.InnerException));
//Invalid - redisplay with errors
return View(model.TicketDetail);
}
}
ViewModel:
public class TicketViewModel
{
public TicketViewModel()
{
TicketDetails = new List<TicketDetail>();
TicketDetail = new TicketDetail();
Ticket = new Ticket();
Tickets = new List<Ticket>();
}
public virtual Ticket Ticket { get; set; }
public virtual IEnumerable<Ticket> Tickets { get; set; }
public virtual TicketDetail TicketDetail { get; set; }
public virtual IEnumerable<TicketDetail> TicketDetails { get; set; }
}
it is also giving error on this "TryUpdateModel(model.TicketDetail);" the error is value cannot be null, please guide me i'm stuck here i have searched internet but couldn't found any appropriate solution. i want to add multiple records
First all properties of your TicketViewModel class have to be instantiated.
To add multiple records (multiple Insert) you could use a StringBuilder and append the insert statements to it. You then have one big query string to be executed on your database.
If using values this is also a valid way:
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
And loading the data to be inserted directly from a file is even faster.
Edit
(after down voting for no reason)
Because some people act like they know it all:
SQL injections are indeed a serious problem when dealing with Database access. That's no secret at all. A common technique to prevent the SQL query from being 'highjacked' you simply use the SQLCommand.Parameters property which is used to map each value individually to the statement to separate the query statement from the data (values) this way. It's now impossible to inject or manipulate statements whithout breaking them. And server side validation is standard to obtain maximum security as well as escaping special input characters and avoiding the use of privilegs with no or low restrictions.
This is NOT a wrong answer.

Categories