Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Just trying to find out if there was a way to do this, only way I found so far was enforcing it myself, I created an attribute to be added to each class where you supply the name of the fields you need to be unique:</p> <pre><code> [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=false,Inherited=true)] public class UniqueAttribute:System.Attribute { private string[] _atts; public string[] KeyFields { get { return _atts; } } public UniqueAttribute(string keyFields) { this._atts = keyFields.Split(new char[]{','}, StringSplitOptions.RemoveEmptyEntries); } } </code></pre> <p>Then in my class I'll add it:</p> <pre><code>[CustomAttributes.Unique("Name")] public class Item: BasePOCO { public string Name{get;set;} [StringLength(250)] public string Description { get; set; } [Required] public String Category { get; set; } [Required] public string UOM { get; set; } [Required] } </code></pre> <p>Finally, I'll add a method in my repository, in the Add method or when Saving Changes like this:</p> <pre><code>private void ValidateDuplicatedKeys(T entity) { var atts = typeof(T).GetCustomAttributes(typeof(UniqueAttribute), true); if (atts == null || atts.Count() &lt; 1) { return; } foreach (var att in atts) { UniqueAttribute uniqueAtt = (UniqueAttribute)att; var newkeyValues = from pi in entity.GetType().GetProperties() join k in uniqueAtt.KeyFields on pi.Name equals k select new { KeyField = k, Value = pi.GetValue(entity, null).ToString() }; foreach (var item in _objectSet) { var keyValues = from pi in item.GetType().GetProperties() join k in uniqueAtt.KeyFields on pi.Name equals k select new { KeyField = k, Value = pi.GetValue(item, null).ToString() }; var exists = keyValues.SequenceEqual(newkeyValues); if (exists) { throw new System.Exception("Duplicated Entry found"); } } } } </code></pre> <p>Not too nice as we need to rely on reflection but this so far is the approach that works for me! =D</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload