in asp.net dynamic date, how to use partial method to validate fields aganist data in database

249 views Asked by At

i want to make sure all product names are unique so i tried to do the following. but it is causing an infinity loop at the lambda expression.

public partial class Product
{
  partial void OnProductNameChanging(string value)
  {
    using(var ctx = new MyEntityContext()){
      var val = value;
      var item = ctx.Products.Where(o=>o.ProductName == val).FirstOrDefault();
      if(item != null)
        throw new ValidationException("Product Name existed.");
    }
  }
}

i'm using asp.net 4.0 with dynamic data and entity framework.

2

There are 2 answers

0
Ash Machine On BEST ANSWER

I am not too familiar with EF, but you should get the changeset and compare values. That is, for the Product Entity and in the case of the the changeset having an Update, compare the EXISTING value with NEW, and change the new in the case of duplication.

Here's how to get changeSet in EF : http://davidhayden.com/blog/dave/archive/2005/11/16/2570.aspx

the comparison and value must be called before any context.SubmitChanges();

Hope this helps.

0
Andy On

Why don't you set it up on database level and handle exeption in case if product name already exists?