How i can force the entity framework to raise a unique exception if the Unique key constraint has been violated on thr sql server database - asp.net-mvc-3

I have a table named countries and i define the country_name field to be unique by creating a “Index/Key” of type “Unique Key” on sql servwer 2008 r2.
But currently if the user insert a country_name value that already exists on my asp.net mvc3 application, then an exception of type “System.Data.Entity.Infrastructure.DbUpdateException” will be raised , which is very general.
So is there a way to define a specific exception in case the unique constraint has been violated ??? rather than just raising the general “System.Data.Entity.Infrastructure.DbUpdateException” exception?
BR

Most likely, thought I can't test it at the moment, the inner exception of DbUpdateException is probably an exception about a duplicate or foreign key constraint. More importantly, you have an opportunity to not throw any exceptions by checking to see if a country already exists. Two ways I can think of are to; check and see if the country already exists by doing a simple select, and if it doesn't, doing an insert/add or write a stored procedure that and do a select/insert or merge and return any value(s) you want back.
Update
(this is example code to demonstrate the logic flow of events and not good programming practice, specially by catching all excepts)
Exception Logic
public AddCountry(string countryTitle)
{
using (var db = new DbContext(_connectionString)
{
try
{
// Linq to (SQL/EF)-ish code
Country country = new Country();
country.ID = Guid.NewGuid();
country.Title = countryTitle;
db.Countrys.Add(country);
db.SubmitChanges(); // <--- at this point a country could already exist
}
catch (DbUpdateException ex)
{
// <--- at this point a country could be delete by another user
throw Exception("Country with that name already exists");
}
}
}
Non-Exception Logic
public AddCountry(string countryTitle)
{
using (var db = new DbContext(_connectionString)
{
using (TransactionScope transaction = new TransactionScope())
{
try
{
Country country = db.Countries
.FirstOrDefault(x => x.Title = countryTitle);
if (country == null)
{
country = new Country();
country.ID = Guid.NewGuid();
country.Title = countryTitle;
db.Countrys.Add(country);
db.SubmitChanges(); // <--- at this point a country
// shouldn't exist due to the transaction
// although someone with more expertise
// on transactions with entity framework
// would show how to use transactions properly
}
}
catch (<someTimeOfTransactionException> ex)
{
// <--- at this point a country with the same name
// should not exist due to the transaction
// this should really only be a deadlock exception
// or an exception outside the scope of the question
// (like connection to sql lost, etc)
throw Exception("Deadlock exception, cannot create country.");
}
}
}
}
Most likely the TransactionScope(Transaction transactionToUse) Constructor would be needed and configured properly. Probably with an Transactions.IsolationLevel set to Serializable
I would also recommend reading Entity Framework transaction.

Related

MVC - Adding data into linker tables

I have a registration form that allows a school to register. In addition to the obvious login and general details the school can pick from a list of facilities and accreditations that they have.
My data is displayed lovely and binded correctly.
Problem Entering the data into the linker tables does not work it throws an error in both the different ways that I have tried:
Method1:
MembershipUser membershipUser = null;
if (schoolRegisterModel != null)
{
if (null != DB)
{
school SchoolUser = new school();
SchoolUser.username = schoolRegisterModel.UserName;
SchoolUser.email = schoolRegisterModel.Email;
string sPassowrdSalt = Security.Instance().CreateSalt();
SchoolUser.password = Security.Instance().CreatePasswordHash(schoolRegisterModel.Password, sPassowrdSalt);
SchoolUser.password_salt = sPassowrdSalt;
..More data etc..
foreach (var item in schoolRegisterModel.Facilities)
{
if (item.#checked)
{
school_facility sf = new school_facility();
sf.facility_id = item.facility_id;
SchoolUser.school_facility.Add(sf);
}
}
foreach (var item in schoolRegisterModel.Accreditations)
{
if (item.#checked)
{
school_accreditation sa = new school_accreditation();
sa.accreditation_id = item.accreditation_id;
SchoolUser.school_accreditation.Add(sa);
}
}
DB.schools.Add(SchoolUser);
DB.SaveChanges();
Error: {"The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_school_facility_facility\". The conflict occurred in database \"MYDB\", table \"dbo.facility\", column 'facility_id'.\r\nThe statement has been terminated."}
Also - Do I need to manually retrieve the soon to be school ID that will be generated based on this insert. This method avoids entering data directly into the linker tables using only the primary table (school).
Method2:
Same code again apart from trying to update the primary tables (school) accreditation and facilities collection directly, I manually update the linker tables seperately using the latest primary key generated by the previous query, code for this is as follows:
MembershipUser membershipUser = null;
if (schoolRegisterModel != null)
{
if (null != DB)
{
school SchoolUser = new school();
SchoolUser.username = schoolRegisterModel.UserName;
SchoolUser.email = schoolRegisterModel.Email;
string sPassowrdSalt = Security.Instance().CreateSalt();
SchoolUser.password = Security.Instance().CreatePasswordHash(schoolRegisterModel.Password, sPassowrdSalt);
SchoolUser.password_salt = sPassowrdSalt;
..More data etc..
// Linker data for facilities and accreditations.
// Facilities
foreach (var item in schoolRegisterModel.Facilities)
{
if (item.#checked)
{
school_facility sf = new school_facility();
sf.facility_id = item.facility_id;
sf.school_id = SchoolUser.school_id;
DB.school_facility.Add(sf);
}
}
// Accreditations
foreach (var item in schoolRegisterModel.Accreditations)
{
if (item.#checked)
{
school_accreditation sa = new school_accreditation();
sa.accreditation_id = item.accreditation_id;
sa.school_id = SchoolUser.school_id;
DB.school_accreditation.Add(sa);
}
}
m_DB.SaveChanges();
Error: {"The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_school_facility_facility\". The conflict occurred in database \"MYDB\", table \"dbo.facility\", column 'facility_id'.\r\nThe statement has been terminated."}
If you guys have any idea where I am going wrong then please do let me know. There seem to be examples of updating linker table date (which I will need at some point anyway) but can't find an example of my problem...
Thanks in advance.
Looks like I have found the answer:
MVC: The INSERT statement conflicted with the FOREIGN KEY constraint
My data being pulled through was basically not containing the correct foreign key value (0 - which didn't exist) and quite rightly my DB was throwing the error. Sorry for wasting time to whoever read and thanks for your time. I hope this can help somebody else.
Joe

Could this be a bug?

I have the following test case
[TestMethod()]
[DeploymentItem("Courses.sdf")]
public void RemoveCourseConfirmedTest()
{
CoursesController_Accessor target = new CoursesController_Accessor();
int id = 50;
ActionResult actual;
CoursesDBContext db = target.db;
Course courseToDelete = db.Courses.Find(id);
List<CourseMeet> meets = courseToDelete.meets.ToList<CourseMeet>();
actual = target.RemoveCourseConfirmed(courseToDelete);
foreach (var meet in meets)
{
Assert.IsNull(db.Meets.find(meet));
}
Assert.IsNull(db.Courses.Find(courseToDelete.courseID));
}
Which tests the following method from my controller.
[HttpPost, ActionName("RemoveCourse")]
public ActionResult RemoveCourseConfirmed(Course course)
{
try
{
db.Entry(course).State = EntityState.Deleted;
db.SaveChanges();
return RedirectToAction("Index");
}
catch (DbUpdateConcurrencyException)
{
return RedirectToAction("RemoveMeet", new System.Web.Routing.RouteValueDictionary { { "concurrencyError", true } });
}
catch (DataException)
{
ModelState.AddModelError(string.Empty, "Unable to save changes. Try again.");
return View(course);
}
}
I know i should be using a Mock db .... but for this project I have decided to go with this approach.
So this what happens. When I run the actual web site this function works perfectly fine and removes the course and all the meets that belong to it.
But when I run the test i get the following exception
System.InvalidOperationException: The operation failed: The relationship could not be
changed because one or more of the foreign-key properties is non-nullable. When a change is
made to a relationship, the related foreign-key property is set to a null value. If the
foreign-key does not support null values, a new relationship must be defined, the foreign-
key property must be assigned another non-null value, or the unrelated object must be
deleted.
Here is the even more interesting part if I comment out the following line from the test
List<CourseMeet> meets = courseToDelete.meets.ToList<CourseMeet>();
and replace the loop with the following:
foreach (var meet in db.Meets.ToList())
{
Assert.IsFalse(meet.courseID == courseToDelete.courseID);
}
I dont get any exceptions and the test case passess.
Am I missing something about Entity Framework or is this a bug?
Well this has been open for a while now. I still haven't been able to find a definite answer but working more with MVC and EF i think what is happening is that once i execute the line
List<CourseMeet> meets = courseToDelete.meets.ToList<CourseMeet>();
the meets get loaded into the object manager and hence when the parent object is deleted the no longer have a reference to the parent course.

Linq InsertOnSubmit is throwing exception: Object reference not set to an instance of an object

The following throws exception.
The course object that is being passed to InsertOnSubmit is of type Course that is generated by Linq.
public ActionResult Course(CourseViewModel c)
{
Course course = (Course) c; //CourseViewModel is derrived from Course
SchedulerDataContext db = new SchedulerDataContext();
db.Courses.InsertOnSubmit(course); // <- this is where exception is thrown
db.SubmitChanges();
}
There are already questions about this here and here, however, I don't understand their answer. Supposedly I'm not creating an object in time. Which object and what exactly needs to happen?
You need to create the Course object before you try to insert it.
Course course = new Course { ... set the properties .. };
SchedulerDataContext db = new SchedulerDataContext();
db.Courses.InsertOnSubmit(course);
db.SubmitChanges();

How to create a update function in LINQ when object has a list?

I´m still having a hard time with Linq.
I need to write a Update Function tat receives an object that has a list. Actually, A region has a list of cities. I want to pass an object "Region" that has a name filed and a list of cities. The problem, is the city objects came from another context and I am unable to attach them to this context. I have been trying several functions, and always get an error like "EntitySet was modified during enumeration" or other. I am tring to make the code below work, but if anyone has a different approach please help.
public int Updateregion(region E)
{
try
{
using (var ctx = new AppDataDataContext())
{
var R =
(from edt in ctx.regiaos
where edt.ID == E.ID
select edt).SingleOrDefault();
if (R != null)
{
R.name = R.name;
R.description = E.description;
}
R.cities = null;
R.cities.AddRange(Edited.Cities);
ctx.SubmitChanges();
return 0 //OK!
}
}
catch (Exception e)
{
......
}
You can't attach objects retrieved from one datacontext to another, it's not supported by Linq-to-SQL. You need to somehow dettach the objects from their original context, but this isn't supported either. One can wonder why a dettach method isn't available, but at least you can fake it by mapping the list to new objects:
var cities = Edited.Cities.Select(city => new City {
ID = city.ID,
Name = city.Name,
/* etc */
});
The key here is to remember to map the primary key and NOT map any of the relation properties. They must be set to null. After this, you should be able to attach the new cities list, and have it work as expected.

How to choose programmatically the column to be queried by Linq using PropertyInfo?

I would like to control how Linq queries my database programmatically. For instance, I'd like to query the column X, column Y, or column Z, depending on some conditions.
First of all, I've created an array of all the properties inside my class called myPropertyInfo.
Type MyType = (typeOf(MyClass));
PropertyInfo[] myPropertyInfo = myType.GetProperties(
BindingFlags.Public|BindingFlags.Instance);
The myPropertyInfo array allows me to access each property details (Name, propertyType, etc) through the index [i].
Now, how can I use the above information to control how Linq queries my DB?
Here's a sample of a query I'd like to exploit.
var myVar = from tp in db.MyClass
select tp.{expression};
Expression using myPropertyInfo[i] to choose which property (column) to query.
I'm not sure if that's the way of doing it, but if there's another way to do so, I'll be glad to learn.
EDIT:
I believe the right expression the one used by #Gabe. In fact, I'd like to make queries on the fly. Here's the reason: I've (i) a table Organizations (Ministries, Embassies, International Organizations, such as UN, UNPD, UNICEF, World Bank, etc, and services depending on them). I've (ii) an other table Hierarchy which represents the way those organizations are linked, starting by which category each one belongs to (Government, Foreign Missions, private sector, NGO, etc.)
Each column representing a level in the hierarchy, some rows will be longer while other will be shorter. Many rows' columns will share the same value (for instance 2 ministries belonging to the government, will have "Government" as value for the column 'Level 1').
That's why, for each row (organization), I need to go level by level (i.e. column by column).
if you're using Entity Framework, not LINQ to SQL, there is wonderful Entity Sql
and you can use it as
object DynamicQuery(string fieldName, object fieldValue) {
string eSql=string.Format("it.{0} = #param", fieldName);
return db.Where(eSql, fieldValue).FirstOrDefault();
}
hope this helps
MSDN has the following example, you see that you can dynamicly change strings used to access ProductID field, and as far as i remember event rename it.
using (AdventureWorksEntities advWorksContext =
new AdventureWorksEntities())
{
try
{
// Use the Select method to define the projection.
ObjectQuery<DbDataRecord> query =
advWorksContext.Product.Select("it.ProductID, it.Name");
// Iterate through the collection of data rows.
foreach (DbDataRecord rec in query)
{
Console.WriteLine("ID {0}; Name {1}", rec[0], rec[1]);
}
}
catch (EntitySqlException ex)
{
Console.WriteLine(ex.ToString());
}
}
Also you can even do the following (again from MSDN)
using (AdventureWorksEntities advWorksContext =
new AdventureWorksEntities())
{
string myQuery = #"SELECT p.ProductID, p.Name FROM
AdventureWorksEntities.Product as p";
try
{
foreach (DbDataRecord rec in
new ObjectQuery<DbDataRecord>(myQuery, advWorksContext))
{
Console.WriteLine("ID {0}; Name {1}", rec[0], rec[1]);
}
}
catch (EntityException ex)
{
Console.WriteLine(ex.ToString());
}
catch (InvalidOperationException ex)
{
Console.WriteLine(ex.ToString());
}
}
It sounds like you want to make a Queryable on-the-fly. I haven't tried it, but this might give you a start:
var myVar =
Queryable.Select(
db.MyClass,
Expression.Property(
Expression.Parameter(
typeof(MyClass), // this represents the type of "tp"
"tp"
),
myPropertyInfo[i]
)
)

Resources