Getting Error When saving changes in database in asp.net mvc4 - c#

This my one method primaryKey of my model is 'PlanetKey'
Graph graph = new Graph();
long lastGraphID = 1000;
//graph.GraphID = lastGraphID;
graph.ItemType = enumType;
graph.GraphItemTitle = title;
graph.GraphItemDescription = statusMessage;
graph.GraphItemUserFullName = null;
graph.GraphItemURL = url;
graph.ItemSummary = title + ": " + statusMessage; ;
graph.ItemCreatedOn = DateTime.UtcNow.ToLocalTime();
//graph.GraphID = lastGraphID;
graph.GraphCustomURL = null;
graph.DbType = "OFFLINE";
graph.ItemOwnerGraphID = ItemOwnerGraphID;
graph.ItemUserID = userInfoId;
graph.PRIMARYTaggedAcademicTreeNodeId = 0;
graph.PRIMARYTaggedAcademicTreeSerialNumber = "1";
graph.PRIMARYTaggedCareerTreeNodeId = 0;
graph.PRIMARYTaggedCareerTreeSerialNumber = "1";
graph.PRIMARYTaggedSkillTreeNodeId = 0;
graph.PRIMARYTaggedSkillTreeSerialNumber = "1";
graph.PRIMARYTaggedAcademicTreeNodeId = 0;
graph.PRIMARYTaggedAcademicTreeSerialNumber = "1";
graph.PRIMARYTaggedToolTreeNodeId = 0;
graph.PRIMARYTaggedToolTreeSerialNumber = "1";
graph.CountReactions = 0;
graph.CountResponses = 0;
graph.CountRatings = 0;
graph.AverageRating = 0;
graph.CountRatings = 0;
graph.CountUses = 0;
graph.CountViews = 0;
graph.isReported = false;
graph.isPSKverified = false;
graph.isPSKbanned = false;
graph.isPSKresource = false;
graph.AccessAllowedCode = 0;
graph.AgeRestrictionCode = loginUserCurrentAge;
graph.isHidden = false;
GraphsController GraphsControllerObject = new GraphsController();
long returnGraphId = GraphsControllerObject.CreateGraphIdByModel(graph);
this is another what i am calling to
public long CreateGraphIdByModel(Graph graph)
{
try
{
if (ModelState.IsValid)
{
db.Graphs.Add(graph);
db.SaveChanges();
return graph.GraphID;
}
}
catch (DataException)
{
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
return graph.GraphID;
}
this is showing me eeror in db.SaveChanges()
what m i doing wrong with this code i just wanna pass my parameter using model as crud of mvc4

To know what the error is: You need to look at the inner exception, it will tell you precisely what the problem is.
You can inspect the exceptions innerException property. It will be an EF exception with a list of errors.
The error says, Error converting datetime2 to datetime
Entity framework handles all the dates as a Datetime2, so, if you fields in the database are Datetime, this could be a problem. Populating all the date fields and changing the datatype, are the most commom solutions
Copied from here: 'datetime2' error when using entity framework in VS 2010 .net 4.0

Related

How to Send Database Table Contents to API?

I have records in a SQL Server database table that need to be transmitted to a payment processing API. Only table records where Transmitted = 0 are to be sent to the API. I found this question which helps me to understand the error at hand.
I want to read the records from my database table into a C# class, parse into JSON, and send via API call. I've tried using Entity Framework Core but receive Null Reference exception when I called the stored procedure and add the results to my model class as follows:
public async Task<IEnumerator<Onboarding>> GetOnboardingList()
{
try
{
using (var context = new SOBOContext())
{
var ob = await context.Onboarding
//.Where(o => o.Transmitted == false)
.FromSql("Execute GetUnsentOnboardingRecords_sp")
.ToListAsync();
Console.WriteLine(ob.ToArray());
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return new OnboardingList().GetEnumerator();
}
When attempting to use Entity Framework Core, I created the OnboardingList class as below:
public class OnboardingList : IEnumerable<Onboarding>
{
private readonly List<Onboarding> _onboarding;
public IEnumerator<Onboarding> GetEnumerator()
{
return _onboarding?.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _onboarding.GetEnumerator();
}
}
I then reverted to SqlDataReader that calls the stored procedure. The method, in part, is as follows:
var listOnboardingModel = new List<Onboarding>();
try
{
using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
{
SqlCommand cmd = new SqlCommand("GetUnsentOnboardingRecords_sp", connection)
{
CommandType = CommandType.StoredProcedure
};
connection.Open();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
listOnboardingModel.Add(new Onboarding
{
OnboardingId = reader[1] as int? ?? 0,
UserId = reader[2] as int?,
UserName = reader[3].ToString(),
FirstName = reader[4].ToString(),
MiddleInitial = reader[5].ToString(),
Lastname = reader[6].ToString(),
DateOfBirth = reader[7].ToString(),
Ssn = reader[8].ToString(),
Email = reader[9].ToString(),
Address1Line1 = reader[10].ToString(),
Address1Line2 = reader[11].ToString(),
Address1ApartmentNumber = reader[12].ToString(),
Address1City = reader[13].ToString(),
Address1State = reader[14].ToString(),
Address1ZipCode = reader[15].ToString(),
Address1Country = reader[16].ToString(),
DayPhone = reader[17].ToString(),
EveningPhone = reader[18].ToString(),
PhonePin = reader[19].ToString(),
MerchantSourceIp = reader[20].ToString(),
ThreatMetrixPolicy = reader[21].ToString(),
SessionId = reader[22].ToString(),
BankAccount1CountryCode = reader[23].ToString(),
BankAccount1Name = reader[24].ToString(),
BankAccount1Description = reader[25].ToString(),
BankAccount1Number = reader[26].ToString(),
BankAccount1OwnershipType = reader[27].ToString(),
BankAccount1Type = reader[28].ToString(),
BankAccount1BankName = reader[29].ToString(),
BankAccount1RoutingNumber = reader[30].ToString(),
BankAccount2CountryCode = reader[31].ToString(),
BankAccount2Name = reader[32].ToString(),
BankAccount2Number = reader[33].ToString(),
BankAccount2OwnershipType = reader[34].ToString(),
BankAccount2Type = reader[35].ToString(),
BankAccount2BankName = reader[36].ToString(),
BankAccount2Description = reader[37].ToString(),
BankAccount2RoutingNumber = reader[38].ToString(),
AuthSginerFirstName = reader[39].ToString(),
AuthSignerLastName = reader[40].ToString(),
AuthSignerTitle = reader[41].ToString(),
AverageTicket = reader[42] as int? ?? 0,
BusinessLegalName = reader[43].ToString(),
BusinessApartmentNumber = reader[44].ToString(),
BusinessAddressLine1 = reader[45].ToString(),
BusinessAddressLine2 = reader[46].ToString(),
BusinessCity = reader[47].ToString(),
BusinessState = reader[48].ToString(),
BusinessZipCode = reader[49].ToString(),
BusinessCountry = reader[50].ToString(),
BusinessDescription = reader[51].ToString(),
DoingBusinessAs = reader[52].ToString(),
Ein = reader[53].ToString(),
HighestTicket = reader[54] as int? ?? 0,
MerchantCategoryCode = reader[55].ToString(),
MonthlyBankCardVolume = reader[56] as int? ?? 0,
OwnerFirstName = reader[57].ToString(),
OwnerLastName = reader[58].ToString(),
OwnerSsn = reader[59].ToString(),
OwnerDob = reader[60].ToString(),
OwnerApartmentNumber = reader[61].ToString(),
OwnerAddress = reader[62].ToString(),
OwnerAddress2 = reader[63].ToString(),
OwnerCity = reader[64].ToString(),
OwnerRegion = reader[65].ToString(),
OwnerZipCode = reader[66].ToString(),
OwnerCountry = reader[67].ToString(),
OwnerTitle = reader[68].ToString(),
OwnerPercentage = reader[69].ToString(),
BusinessUrl = reader[70].ToString(),
CreditCardNumber = reader[71].ToString(),
ExpirationDate = reader[72].ToString(),
NameOnCard = reader[73].ToString(),
PaymentMethodId = reader[74].ToString(),
PaymentBankAccountNumber = reader[75].ToString(),
PaymentBankRoutingNumber = reader[76].ToString(),
PaymentBankAccountType = reader[77].ToString(),
Transmitted = reader[78] as bool?,
TransmitDate = reader[79].ToString(),
InternationalId = reader[80].ToString(),
DriversLicenseVersion = reader[81].ToString(),
DocumentType = reader[82].ToString(),
DocumentExpDate = reader[83].ToString(),
DocumentIssuingState = reader[84].ToString(),
MedicareReferenceNumber = reader[85].ToString(),
MedicareCardColor = reader[86].ToString(),
PaymentBankAccountName = reader[87].ToString(),
PaymentBankAccountDescription = reader[88].ToString(),
PaymentBankCountryCode = reader[89].ToString(),
PaymentBankName = reader[90].ToString(),
PaymentBankOwnershipType = reader[91].ToString()
});
}
}
connection.Close();
}
Console.WriteLine(listOnboardingModel);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return listOnboardingModel;
When I run the console application, I receive the Error Exception thrown: 'System.IndexOutOfRangeException' in System.Data.SqlClient.dll
Index was outside the bounds of the array.
How do I prevent the above out of range exception and also ensure that all qualifying records from my database table are included for transmission?
You appear to have two distinct issues:
You .ToString() a null value, which causes null reference exception.
An ordinal is likely out of bounds, a column does not match the numeric value provided causing it to be out of bounds.
Check for DBNull.Value otherwise bullet point one will occur.
My assumption would be that you start with one, while index's are zero based. So the first column would start at zero not one.
You should lookup Dapper or some built in utilities for SqlDataReader to leverage cleaner code calls to build your object. Dapper would condense the code by simply doing:
IEnumerable<Sample> GetSamples() => dbConnection.Query<Sample>(...);
As long as the column name matches the property name, it'll populate. Based on the entity provided it looks pretty simple, but checkout the documentation.
Also you should wrap command in using statement like, that way you do not have someone accidentally call a command.Dispose() in the middle of your connection block on accident:
using(var connection = new SqlConnection(...))
using(var command = new SqlCommand(..., ...))
{
connection.Open();
...
using(var reader = command.ExecuteReader())
while(reader.Read())
{
}
}

Validation error when attempting to SaveChanges to table

I am rather new to the whole programming with C# and I stumbled upon a small problem that I just cannot solve.
I start up the software the code below is programmed into and it is working well until it reaches the SaveChanges call and it throws an error:
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
I have already attempted to inspect EntityValidationErrors, but it doesn't want to show me any errors at all. So I am turning to you all to find some answers.
//
// GET: /Installningar/FoxImportTidning
public async Task<ActionResult> FoxImportTidning()
{
Tidning tidning = new Tidning();
SaveTidningToDatabase("C:/Backup/Prenback/backuptidning.xls");
return View();
}
//
// POST: /Installningar/FoxImportTidning
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> FoxImportTidning(Tidning Id)
{
if (ModelState.IsValid)
{
db.Entry(Id).State = EntityState.Modified;
await db.SaveChangesAsync();
Main.PopulateGlobalInst();
ViewBag.SaveMsg = "Sparat!";
return RedirectToAction("Main", "Main", new { Id = Id.Id });
}
return View(Id);
}
private ApplicationDbContext databas6 = new ApplicationDbContext();
private string SaveTidningToDatabase(string filePath)
{
String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath);
using (OleDbConnection excelConnection = new OleDbConnection(excelConnString))
{
using (OleDbCommand cmd = new OleDbCommand("Select * from [backuptidning$]", excelConnection))
{
excelConnection.Open();
var tidningLista = new List<Tidning>();
databas6.Tidnings.Clear();
databas6.SaveChanges();
using (OleDbDataReader dReader = cmd.ExecuteReader())
do
{
while (dReader.Read())
{
Object[] tidninginfo = new Object[45];
int id = Convert.ToInt32(dReader[0]);
string namn = Convert.ToString(dReader[1]);
string datadir = Convert.ToString(dReader[2]);
string adr1 = Convert.ToString(dReader[3]);
string adr2 = Convert.ToString(dReader[4]);
string regnr = Convert.ToString(dReader[5]);
string tel = Convert.ToString(dReader[6]);
string pg = Convert.ToString(dReader[7]);
string bg = Convert.ToString(dReader[8]);
string villkor = Convert.ToString(dReader[9]);
int sista_nr = Convert.ToInt32(dReader[10]);
int faktavg = Convert.ToInt32(dReader[11]);
int vilande = Convert.ToInt32(dReader[12]);
int listlopnr = Convert.ToInt32(dReader[13]);
int faktnr = Convert.ToInt32(dReader[14]);
decimal moms = Convert.ToDecimal(dReader[15]);
int avipriskod = Convert.ToInt32(dReader[16]);
DateTime? inbetdat = null;
try
{
inbetdat = Convert.ToDateTime(dReader[17]);
}
catch { }
int period = Convert.ToInt32(dReader[18]);
string avityp = Convert.ToString(dReader[19]);
DateTime? sistavidat = null;
try
{
sistavidat = Convert.ToDateTime(dReader[20]);
}
catch { }
DateTime? fromdatum = null;
try
{
fromdatum = Convert.ToDateTime(dReader[21]);
}
catch { }
DateTime? tomdatum = null;
try
{
tomdatum = Convert.ToDateTime(dReader[22]);
}
catch { }
int fromprennr = Convert.ToInt32(dReader[23]);
int tomprennr = Convert.ToInt32(dReader[24]);
string databasversion = Convert.ToString(dReader[25]);
int nummerperiod = Convert.ToInt32(dReader[26]);
int nolastyear = Convert.ToInt32(dReader[27]);
int nonextyear = Convert.ToInt32(dReader[28]);
string dubbelnummer = Convert.ToString(dReader[29]);
bool skrivetik = Convert.ToBoolean(dReader[30]);
bool utrmomsavdrag = Convert.ToBoolean(dReader[31]);
bool buntning = Convert.ToBoolean(dReader[32]);
int pren = Convert.ToInt32(dReader[33]);
int betalare = Convert.ToInt32(dReader[34]);
int kredit = Convert.ToInt32(dReader[35]);
int fornyanr = Convert.ToInt32(dReader[36]);
string landskod = Convert.ToString(dReader[37]);
DateTime? nästsist = null;
try
{
nästsist = Convert.ToDateTime(dReader[38]);
}
catch { }
string fax = Convert.ToString(dReader[39]);
string epost = Convert.ToString(dReader[40]);
string hemsida = Convert.ToString(dReader[41]);
string bic = Convert.ToString(dReader[42]);
string iban = Convert.ToString(dReader[43]);
string faktkoll = Convert.ToString(dReader[44]);
var tidning = new Tidning();
tidning.Id = id;
tidning.Namn = namn;
tidning.Datadir = datadir;
tidning.Adr1 = adr1;
tidning.Adr2 = adr2;
tidning.Regnr = regnr;
tidning.Tel = tel;
tidning.Pg = pg;
tidning.Bg = bg;
tidning.Villkor = villkor;
tidning.Sista_nr = sista_nr;
tidning.FaktAvg = faktavg;
tidning.Vilande = vilande;
tidning.Listlopnr = listlopnr;
tidning.Faktnr = faktnr;
tidning.Moms = moms;
tidning.AviPriskod = avipriskod;
tidning.InbetDatum = inbetdat;
tidning.Period = period;
tidning.AviTyp = (AviTyp)Enum.Parse(typeof(AviTyp), avityp, true);
tidning.SistAviDatum = sistavidat;
tidning.FromDatum = fromdatum;
tidning.TomDatum = tomdatum;
tidning.FromPrennr = fromprennr;
tidning.TomPrennr = tomprennr;
tidning.Databasversion = databasversion;
tidning.Nummerperiod = nummerperiod;
tidning.Nolastyear = nolastyear;
tidning.Nonextyear = nonextyear;
tidning.Dubbelnummer = dubbelnummer;
tidning.Skrivetik = skrivetik;
tidning.Utrmomsavdrag = utrmomsavdrag;
tidning.Buntning = buntning;
tidning.Pren = pren;
tidning.Betalare = betalare;
tidning.Kredit = kredit;
tidning.Fornyanr = fornyanr;
tidning.Landskod = landskod;
tidning.NastSist = nästsist;
tidning.Fax = fax;
tidning.Epost = epost;
tidning.Hemsida = hemsida;
tidning.Bic = bic;
tidning.Iban = iban;
tidning.Faktkoll = faktkoll;
tidningLista.Add(tidning);
}
} while (dReader.NextResult());
databas6.Tidnings.AddRange(tidningLista);
databas6.SaveChanges(); //<--- This is where it goes wrong
excelConnection.Close();
return ("hej"); //<--- Do not mind this one
}
}
}
If you need any further information, just tell me and I will provide it. The main thing I want is to get this working and this is not the only code giving me this problem, but if this one can be solved, then maybe the other ones can be solved the same way.
This error is caused when you are trying to add invalid data to your database table.
e.g. you are adding string of 100 chars to the table column but in table definition your column has maxlength of 50. in that case value you are adding is invalid as per the column definitions and this error occur.
you should log what properties are causing the error. for that you can use below code:
catch (System.Data.Entity.Validation.DbEntityValidationException ex)
{
Logger.WriteError("{0}{1}Validation errors:{1}{2}", ex, Environment.NewLine, ex.EntityValidationErrors.Select(e => string.Join(Environment.NewLine, e.ValidationErrors.Select(v => string.Format("{0} - {1}", v.PropertyName, v.ErrorMessage)))));
throw;
}
You can catch these errors easily ,using the watch window, without writing much code.
Kindly find the very good solution in the following link
https://stackoverflow.com/a/40732784/3397630
I really inspired in the way that answer was given, with the very good screenshots . Sharing it here with the hope it will be helpful to you and the others.
thanks
KArthik

Creating User in dotnetnuke and Assign Role using c#

I'm trying to create a user programatically using C# in dnn. When ever I execute the code below, it throws object reference error. I tried breaking the code and I found out that its not getting inside the if (result == UserCreateStatus.Success) statement. Whenever I point my mouse to the result instant, it shows an invalid password message. The thing is that I have used this same code before somewhere else and its working fine. I even copied what I used earlier on but its keeps showing the same error. Please is there anything I'm missing?
//Generating 8 char passwor
Random adomRng = new Random();
string rndString = string.Empty;
char c;
for (int i = 0; i < 8; i++)
{
while (!Regex.IsMatch((c = Convert.ToChar(adomRng.Next(48, 128))).ToString(), "[A-Za-z0-9]")) ;
rndString += c;
}
string space = " ";
UserInfo oUser = new UserInfo();
oUser.PortalID = this.PortalId;
oUser.IsSuperUser = false;
oUser.FirstName = Session["fname"].ToString();
oUser.LastName = Session["lname"].ToString();
oUser.Email = Session["email"].ToString();
oUser.Username = Session["username"].ToString();
oUser.DisplayName = Session["fname"].ToString() + space.ToString() + Session["lname"].ToString();
//Fill MINIMUM Profile Items (KEY PIECE)
oUser.Profile.PreferredLocale = PortalSettings.DefaultLanguage;
//oUser.Profile.PreferredTimeZone =PortalSettings.TimeZoneOffset;
oUser.Profile.FirstName = oUser.FirstName;
oUser.Profile.LastName = oUser.LastName;
//Set Membership 17:
UserMembership oNewMembership = new UserMembership();
oNewMembership.Approved = true;
oNewMembership.CreatedDate = System.DateTime.Now;
oNewMembership.Email = oUser.Email;
oNewMembership.IsOnLine = false;
oNewMembership.Username = oUser.Username;
oNewMembership.Password = rndString;
UserCreateStatus result = UserController.CreateUser(ref oUser);
if (result == UserCreateStatus.Success)
{
RoleController oDnnRoleController = new RoleController();
//Get the role information
RoleInfo oCurrentRole = oDnnRoleController.GetRoleByName(this.PortalId, Request.QueryString["TSORole"].ToString());
// RoleInfo oCurrentRole1 = oDnnRoleController.GetRoleByName(this.PortalId, " Subscribers");
//Assign to user
oDnnRoleController.AddUserRole(this.PortalId, oUser.UserID, oCurrentRole.RoleID, Null.NullDate, Null.NullDate);
// oDnnRoleController.DeleteUserRole(this.PortalId, int.Parse(oUser.UserID.ToString()), oCurrentRole.RoleID);
}
The reason why same code works for one and not the other could be different password rules for these websites. Make sure you are generating a password that complies with the password requirements of the target website.

Get Stack Overflow questions with Stacky API

I want to get the most current questions from Stack Overflow using the Stacky C# library for the Stack Exchange API.
I took the example code and tried to run it but it hangs when it comes to returning data from the Stack Exchange website.
StackyClient client = new StackyClient("0.9", "", Sites.StackOverflow,
new UrlClient(), new JsonProtocol());
var o = new QuestionOptions();
o.FromDate = DateTime.Now.AddMinutes(-10.0);
o.ToDate = DateTime.Now;
o.IncludeAnswers = false;
o.IncludeBody = false;
o.IncludeComments = false;
o.SortBy = QuestionSort.Creation;
o.SortDirection = SortDirection.Descending;
IPagedList<Question> l = client.GetQuestions(o); <--- program hangs here 4ever
What am I doing wrong?
I also saw that I can register my application to get an API Key. But that is not necessary to make it run in the first place, is it?
Edit
If I remove the lines
o.FromDate = DateTime.Now.AddMinutes(-10.0);
o.ToDate = DateTime.Now;
it works and returns all questions. Also if I add the line
o.Max = 50;
instead, then it does not work either.
Edit 2
Now it works - rebooted my computer.
BTW I used that code in the end
var o = new QuestionOptions();
o.FromDate = DateTime.UtcNow.AddMinutes(-20);
o.IncludeAnswers = false;
o.IncludeBody = false;
o.IncludeComments = false;
o.SortBy = QuestionSort.Creation;
o.SortDirection = SortDirection.Descending;
IPagedList<Question> l = client.GetQuestions(o);
And
o.Max
expects an Unix Epoch time, not a number of maximum posts.
Try changing the version specified in the StackyClient constructor from "0.9" to "1.1". I get a JSON parse error on the client.GetQuestions(o) line when the version is "0.9", but it runs fine with "1.1".
Using the latest Stacky code from bitbucket there is no longer a QuestionOptions parameter to GetQuestions. Also using version 0.9 of the API causes Stacky to crash, but according to this version 1.x is deprecated, so maybe 0.9 is removed?
StackyClient client = new StackyClient("2.1", Sites.StackOverflow,
new UrlClient(), new JsonProtocol());
//var o = new QuestionOptions();
//o.FromDate = DateTime.Now.AddMinutes(-10.0);
//o.ToDate = DateTime.Now;
//o.IncludeAnswers = false;
//o.IncludeBody = false;
//o.IncludeComments = false;
//o.SortBy = QuestionSort.Creation;
//o.SortDirection = SortDirection.Descending;
QuestionSort sort = QuestionSort.Creation;
SortDirection sortDir = SortDirection.Descending;
int page = 1;
int pageSize = 100;
DateTime fromDate = DateTime.Now.AddMinutes(-10.0);
DateTime toDate = DateTime.Now;
IPagedList<Question> l = client.GetQuestions(sort, sortDir, page, pageSize, fromDate, toDate);
foreach (var question in l)
{
Console.WriteLine(question.Title);
}
Or, just remove the date and see if you get any results.
IPagedList<Question> l = client.GetQuestions(sort, sortDir, page, pageSize);//, fromDate, toDate);
foreach (var question in l)
{
Console.WriteLine(question.Title);
}

Linq Entity Exception not printing error

I am LINQ to input information from a Database. I have my try.catch block set up to catch these exceptions. However I believe I ran into a sore spot where I am attempting to see what the message is but it just bypass printing the message to me and goes directly to error page. Here is an example of the code I have so far. I would love to get some input on why this seems to be acting so strange.
private void CreateEntry()
{
var date = DateTime.Today;
var version = (from v in house.StayLateVersions
where v.Active
select v).FirstOrDefault();
if (version == null)
{
throw new NullReferenceException();
}
//Try to create an entry for the database. Upon failure, sends the exception to ThrowDbError();
try
{
ResidenceHallInspection rhi = new ResidenceHallInspection();
rhi.versionId = version.id;
rhi.submitDate = DateTime.Now;
rhi.CheckInOrOut = ddlCheck.SelectedItem.Text;
rhi.Id = txtId.Text;
rhi.FirstName = txtFirstName.Text;
rhi.MiddleName = txtMiddleName.Text;
rhi.LastName = txtLastName.Text;
rhi.Walls = chbxWalls.SelectedItem.Text;
rhi.Windows = chbxWindows.SelectedItem.Text;
rhi.Blinds = chbxBlinds.SelectedItem.Text;
rhi.Couch = chbxCouch.SelectedItem.Text;
rhi.CommonRoomCouch = chbxCRCouch.SelectedItem.Text;
rhi.CommonRoomChair = chbxCRChair.SelectedItem.Text;
rhi.Doors = chbxDoors.SelectedItem.Text;
rhi.Carpet = chbxCarpet.SelectedItem.Text;
rhi.Ceiling = chbxCeiling.SelectedItem.Text;
rhi.CommonRoomCounter = chbxCRCounter.SelectedItem.Text;
rhi.Cabinet = chbxCabinet.SelectedItem.Text;
rhi.Phone = chbxPhone.SelectedItem.Text;
rhi.Bed = chbxBed.SelectedItem.Text;
rhi.Desk = chbxDesk.SelectedItem.Text;
rhi.DeskChairs = chbxDeskChair.SelectedItem.Text;
rhi.Tub = chbxTub.SelectedItem.Text;
rhi.Vanity = chbxVanity.SelectedItem.Text;
rhi.Notes = txtNotes.Text;
rhi.Building = txtResHall.Text;
rhi.ApartmentNumber = txtSuitNo.Text;
rhi.BedSpace = txtBedSpace.Text;
house.AddToResidenceHallInspections(rhi);
house.SaveChanges();
}
catch (Exception oe)
{
ThrowDbError(oe);
Response.Write(oe.InnerException);
}
}
/*=================================================*/
/*Possible Errors */
/*=================================================*/
private void ThrowDbError(Exception oe)
{
Response.Write(oe.Source);
house.Dispose();
Session.Contents.Add("FormException", oe);
Response.Redirect("/Database-Error/", true);
}
The most likely reason for that to happen is that you are running the database version query outside the try/catch block. Any exception in this db access code will not be handled by the code you have shown above.
Try extending your try block to also include the db access code:
var version = (from v in house.StayLateVersions
where v.Active
select v).FirstOrDefault();
if (version == null)
{
throw new NullReferenceException();
}
and see if this time the error is caught.

Categories

Resources