locked
Detect UNIQUE Key constraint violation using OnValidate? RRS feed

  • Question

  • User1204604062 posted

    Hello, I have a table with  a UNIQUE constraint on a column, I want to be able to throw a friendly message to the customer but I cant find how, on the isert and on the update.

     

    partial void OnValidate(System.Data.Linq.ChangeAction action)
            {
                if (action == System.Data.Linq.ChangeAction.Delete)
                {
                    if (this.PreventiveWorkOrderAssets.Count > 0 || PreventiveWorkOrderHistoryAssets.Count>0)
                    {
                        throw new Exception("No se pueden eliminar activos asociadas a ordenes de trabajo preventivas");
                    }
                    if(this.Services.Count>0)
                    {
                        throw new Exception("No se pueden eliminar activos asociadas a servicios del modulo correctivo.");
                    }
                    if (this.ContractAssets.Count > 1)
                    {
                        throw new Exception("No se pueden eliminar activos asociadas a un contrato.");
         
                    }
                    if (action == System.Data.Linq.ChangeAction.Insert)
                    {
                        if(this.
                    }
                }
            } 

    Monday, December 22, 2008 2:07 PM

Answers

  • User-1005219520 posted

    This exact question has come up a couple times - while I look for the posts - take a look at David's Handling database exceptions in Dynamic Data - which might get you started.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, December 22, 2008 2:55 PM
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, December 22, 2008 3:10 PM
  • User-330204900 posted

    It must be spelt wrong then, if you try adding just the data context partial class and namespacew if required: 

    public partial class BFDataContext : System.Data.Linq.DataContext
    {
        partial
    }

    Then inside the braces press enter and type partial and a space it should offer intellisense for the correct methods, that way you will get it right, also it save on typing [:D]

     Hope this helps [:D]

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, December 23, 2008 2:07 PM

All replies

  • User-1005219520 posted

    This exact question has come up a couple times - while I look for the posts - take a look at David's Handling database exceptions in Dynamic Data - which might get you started.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, December 22, 2008 2:55 PM
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, December 22, 2008 3:10 PM
  • User1204604062 posted
     
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using Paradigma.Utilities.Attributes;
    using Microsoft.Web.DynamicData;
    
    namespace Sodexo.Data
    {
    
    
    
        [MetadataType(typeof(AssetMetaData))]
        [DisplayColumn("Name", "Name", false)]
        public partial class Asset
        {
            private ModelDataContext data = ModelDataContext.Instance;
    
            partial void OnValidate(System.Data.Linq.ChangeAction action)
            {
                if (action == System.Data.Linq.ChangeAction.Delete)
                {
                    if (this.PreventiveWorkOrderAssets.Count > 0 || PreventiveWorkOrderHistoryAssets.Count>0)
                    {
                        throw new Exception("No se pueden eliminar activos asociadas a ordenes de trabajo preventivas");
                    }
                    if(this.Services.Count>0)
                    {
                        throw new Exception("No se pueden eliminar activos asociadas a servicios del modulo correctivo.");
                    }
                    if (this.ContractAssets.Count > 1)
                    {
                        throw new Exception("No se pueden eliminar activos asociadas a un contrato.");
          
                    }
                    if (action == System.Data.Linq.ChangeAction.Insert)
                    { 
                    }
                }
            }
    
            public override void SubmitChanges(System.Data.Linq.ConflictMode failureMode)
            {
                try
                {
                    base.SubmitChanges(failureMode);
                }
                catch (Exception e)
                {
                    throw new ValidationException(null, e);
                }
            }
     
            public int Save()
            {
                data.Assets.InsertOnSubmit(this);
                data.SubmitChanges();
                return this.Id;
            }
    
            public void Update()
            {
                data.SubmitChanges();
            }
    
            public void Delete()
            {
                data.Assets.DeleteOnSubmit(this);
                data.SubmitChanges();
            }
    
            public static List<asset> GetAssets()
            {
                List<asset> assets = null;
                //assets = ModelDataContext.Instance.GetAssets(null).ToList();
    
                return assets;
            }
    
            public static Asset GetAsset(int assetId)
            {
                Asset asset = null;
                //asset = ModelDataContext.Instance.GetAssets(assetId).Single();
    
                return asset;
            }
    
    
            public static List<asset> GetAssets(Guid assetTypeId)
            {
                List<asset> assets = null;
                //assets = (from a in ModelDataContext.Instance.Assets
                //              where a.AssetTypeId == assetTypeId
                //                select a).ToList();
    
                return assets;
            }
    
            public static List<asset> GetAssetsByDependency(int DependencyId)
            {
                List<asset> assets = null;
                assets = (from a in ModelDataContext.Instance.Assets
                          where a.DependencyId==DependencyId && a.State==true
                          select a).ToList();
    
                return assets;
            }
    
    
            public List<asset> SearchByLetter(string Letter)
            {
                List<asset> assets = null;
                assets = (from a in ModelDataContext.Instance.Assets
                          where a.Name.StartsWith(Letter)
                          select a).ToList();
    
                return assets;
            }
    
            public static List<asset> GetFilteredAssets(int? regionalId, int? cityId, int? dependencyId,
                int? serviceType, bool? withWorkOrder, string placa, string serial,
                DateTime? minDueDate, DateTime? maxDueDate, int? supplierId,bool? state)
            {
                List<asset> assets = new List<asset>();
    
                assets = ModelDataContext.Instance.Assets
                    .FromRegional(regionalId)
                    .FromCity(cityId)
                    .FromDependency(dependencyId)
                    .FilterByServiceType(serviceType)
                    .WithWorkOrder(withWorkOrder)
                    .WithPlaca(placa)
                    .WithSerial(serial)
                    .WorkOrderDuedFrom(minDueDate)
                    .WorkOrderDuedTo(maxDueDate)
                    .AssignedTo(supplierId)
                    .State(state)
                    .ToList();
               
    
    
                return assets;
            }
        }
    
        [DisplayName("Activos")]
        public class AssetMetaData
        {
            [ScaffoldColumn(false)]
            public object Id { get; set; }
            
            [DisplayName("Nombre")]
            [Required(ErrorMessage = "Este campo es Requerido")]
            public object Name { get; set; }
    
            [Required(ErrorMessage = "Este campo es Requerido")]
            [DisplayName("Descripción")]
            [HideColumnIn(PageTemplate.List)]
            public object Description { get; set; }
    
            [Required(ErrorMessage = "Este campo es Requerido")]
            [DisplayName("Marca")]
            public object Brand { get; set; }
    
            [Required(ErrorMessage = "Este campo es Requerido")]
            [DisplayName("Modelo")]
            public object Model { get; set; }
    
            [Required(ErrorMessage = "Este campo es Requerido")]
            [DisplayName("Serial")]
            public object Serial { get; set; }
    
            [Required(ErrorMessage = "Este campo es Requerido")]
            [DisplayName("Ubicación")]
            [HideColumnIn(PageTemplate.List)]
            public object Location { get; set; }
    
            [DisplayName("Dependencia")]
            [HideColumnIn(PageTemplate.List)]
            [Required(ErrorMessage = "Este campo es Requerido")]        
            public object Dependency { get; set; }
    
            [Required(ErrorMessage = "Este campo es Requerido")]
            [DisplayName("Capacidad")]
            [HideColumnIn(PageTemplate.List)]
            public object Capacity { get; set; }
    
            [DisplayName("Tipo de Servicio")]
            [HideColumnIn(PageTemplate.List)]
            [Required(ErrorMessage = "Este campo es Requerido")]        
            public object ServiceType { get; set; }
    
            [DisplayName("Garantia")]
            [HideColumnIn(PageTemplate.List)]
            public object Warranty { get; set; }
    
            [DisplayName("Fecha de Compra")]
            [HideColumnIn(PageTemplate.List)]
            [UIHint("DateAjaxCalendar")]
            [Required(ErrorMessage = "Este campo es Requerido")]
            public object PurchaseDate { get; set; }
    
            [DisplayName("Fecha de Garantía")]
            [HideColumnIn(PageTemplate.List)]
            [UIHint("DateAjaxCalendar")]
            [Required(ErrorMessage = "Este campo es Requerido")]
            public object WarrantyDate { get; set; }
    
            [DisplayName("Fecha de Instalación")]
            [HideColumnIn(PageTemplate.List)]
            [UIHint("DateAjaxCalendar")]
            [Required(ErrorMessage = "Este campo es Requerido")]
            public object InstallationDate { get; set; }
    
            [DisplayName("Placa")]
            [Required(ErrorMessage = "Este campo es Requerido")]
            public object Placa { get; set; }
    
            [DisplayName("Activo")]
            [HideColumnIn(PageTemplate.List)]
            [UIHint("Boolean")]
            [Filter(Enabled=true)]
            public object State { get; set; }
    
            [ScaffoldColumn(false)]
            public object ContractAssets { get; set; }
    
            [ScaffoldColumn(false)]
            public object Services { get; set; }
         
            [ScaffoldColumn(false)]
            public object PreventiveWorkOrderAssets { get; set; }
    
            [ScaffoldColumn(false)]
            public object PreventiveWorkOrderHistoryAssets { get; set; }
        }
    }
    </asset></asset></asset></asset></asset></asset></asset></asset></asset></asset></asset>
     

     I tried this:

     

    public override void SubmitChanges(System.Data.Linq.ConflictMode failureMode)
            {
                try
                {
                    base.SubmitChanges(failureMode);
                }
                catch (Exception e)
                {
                    throw new ValidationException(null, e);
                }
            }

     

    And it tells me the object does not have a deffinition for SubmitChanges

     

     

    Monday, December 22, 2008 3:30 PM
  • User-1005219520 posted
    SubmitChanges is only in the L2S model - you must be using EF. Look in your data model.

     

    Monday, December 22, 2008 3:36 PM
  • User1204604062 posted

     I tried the following approach but its weird because it never gets to the break point.

     

     

       public int Save()
    {
    var Asset = Sodexo.Data.ModelDataContext.Instance.Assets.FirstOrDefault(c => c.Placa == this.Placa);

    if (Asset != null)
    {
    throw new ValidationException("La placa ingresada ya existe.");
    }
    else
    {
    data.Assets.InsertOnSubmit(this);
    data.SubmitChanges();
    return this.Id;
    }



    }

    public void Update()
    {
    var Asset = Sodexo.Data.ModelDataContext.Instance.Assets.FirstOrDefault(c => c.Placa == this.Placa);

    if (Asset != null)
    {
    throw new ValidationException("La placa ingresada ya existe.");
    }
    else
    {
    // data.Assets.InsertOnSubmit(this);
    data.SubmitChanges();
    //return this.Id;
    }
    }

      

     

    However, I did a temporary solution on the list.aspx.cs

     

    protected void OnDetailsViewItemInserted(object sender, DetailsViewInsertedEventArgs e)
            {
                if (e.Exception != null )
                {
                    ResultMessage1.MessageType = ResultMessage.MessageTypes.Error;
                    if(e.Exception.Message.Contains("Violation of UNIQUE KEY"))
                    {
                           ResultMessage1.Message = "No puede ingresar un activo con placa duplicada";
                    }
                    else
                    {
                        ResultMessage1.Message = e.Exception.Message;
                    }
                    e.ExceptionHandled = true;
                }
                else
                {
                    ResultMessage1.MessageType = ResultMessage.MessageTypes.Success;
                    ResultMessage1.Message = "El registro se ingresó con éxito";
                    GridView1.DataBind();
                }
            }
     

    Monday, December 22, 2008 3:44 PM
  • User-1005219520 posted

    >> I tried the following approach but its weird because it never gets to the break point.

    That usually indicates you don't have the correct namespace around your partial class. Use the same namespace as your data model.

    Monday, December 22, 2008 3:55 PM
  • User1204604062 posted

     Thanks but its on the same namespace.

    Monday, December 22, 2008 4:32 PM
  • User-330204900 posted

    It must be spelt wrong then, if you try adding just the data context partial class and namespacew if required: 

    public partial class BFDataContext : System.Data.Linq.DataContext
    {
        partial
    }

    Then inside the braces press enter and type partial and a space it should offer intellisense for the correct methods, that way you will get it right, also it save on typing [:D]

     Hope this helps [:D]

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, December 23, 2008 2:07 PM
  • User1980140492 posted

    Is this still the way to go ( EF ):
    http://blogs.msdn.com/b/davidebb/archive/2008/12/11/handling-database-exceptions-in-dynamic-data.aspx

    Or is there a "newer" way for .NET 4.0?

     

    Wednesday, July 13, 2011 9:50 AM
  • User-330204900 posted

    Hi Yannick, yes EF is the way going forward EF always had the most potential and since .Net 4 it is going form strength to strength see Announcing the Microsoft Entity Framework June 2011 CTP also remember we recently had EF 4.1.

    Also remember Microsoft have not abandoned Linq to SQL but they are putting most effort into EF so long term EF it the way to go.

    Friday, July 15, 2011 5:22 AM