I use EF 3.5 and have a db with a category table. I've created a partial class to expand the class created by EF. I have CategoryId as a key in the db and it is set to Identity in the model. This is my partial class:
public partial class Category
{
public Category(开发者_JS百科string name, bool isChild)
{
this.CatName = name;
this.IsChild = isChild;
}
public bool Save()
{
try
{
using (var context = new PhonebookEntities())
{
context.AddToCategories(this);
context.SaveChanges();
}
return true;
}
catch (System.Exception)
{
return false;
}
}
}
But when I try to create a new Category object and save it..:
var category = new Category("Test", false);
category.Save();
I get this exception: "Violation of UNIQUE KEY constraint 'IX_Category'. Cannot insert duplicate key in object 'dbo.Category'.\r\nThe statement has been terminated." I should mention that a category has a reference to itself because it can have a parent category through a nullable int which points to the categoryid to the parent category.
What is the contents of IX_Category? If it is not needed, delete it. Is there another category with "Test" as its CatName in your database? Is IX_Category a unique key constraint on the CatName field?
精彩评论