2
\$\begingroup\$

I have a service to Insert TagName , I dont want to insert duplicate tags I used this :

   public void Insert(string tagName)
    {
        tagName = tagName.Trim();

        if (IsExists(tagName))
            throw new ArgumentException("tagName is Exists");
        Tag model = new Tag { Name=tagName};

        _uow.MarkAsAdded(model);

    }

    public bool IsExists(string tagName)
    {
        return _tags.Any(row=>row.Name==tagName.Trim());
    }

and another way is change If statement like below :

  public void Insert(string tagName)
    {
        tagName = tagName.Trim();

        if (!IsExists(tagName))
        {
            Tag model = new Tag { Name = tagName };
            _uow.MarkAsAdded(model);
        }
    }

I decided to use second one because I add another method Like this :

  public void Insert(string[] tags)
    {
        foreach (var item in tags)
        {
            Insert(item);
        }
    }

If I throw exception , Insert(string[] tags) will not completed .

Updated:

 private readonly IDbSet<Tag> _tags;

      #region ctor

    public TagService(IUnitOfWork uow)
    {
        _uow = uow;
        _tags = _uow.Set<Tag>();

    }

    #endregion
\$\endgroup\$
3
\$\begingroup\$

You make this harder then it needs to be.

Since IDbSet implements the IEnumerable<TEntity> interface

 public interface IDbSet<TEntity> 
 : IQueryable<TEntity>, IEnumerable<TEntity>, IQueryable, IEnumerable

you can simply use the Contains extension optionally with your own comparer that can implement such things as Trim etc.

\$\endgroup\$
  • \$\begingroup\$ I used Trim() beacse I don't want to save Tag name with spaces around it , Like this C# or ` MVC ` \$\endgroup\$ – work question Jul 12 '17 at 10:20
  • 1
    \$\begingroup\$ @workquestion sure, I'm not saying that it's wrong just that you could put it in the comparer and call it again just before adding a new tag. \$\endgroup\$ – t3chb0t Jul 12 '17 at 10:22
  • 2
    \$\begingroup\$ @t3chb0t - I don't think a comparer is the right choice for encoding important domain rules. Here, the OP is saying Tagname must never have surrounding whitespace. I think Trimming incoming values is a better choice (but that's up for debate!) \$\endgroup\$ – RobH Jul 12 '17 at 10:47
  • \$\begingroup\$ @RobH true, I always say there should be multiple sting types for this, case-insensitive and trimmed ones becasue this two are causing too many bugs. \$\endgroup\$ – t3chb0t Jul 12 '17 at 10:59
  • \$\begingroup\$ @t3chb0t - I know what you mean... Especially with SQL's handling of equality see here. It's easy to have stuff in the DB returning true and stuff in C# returning false if you don't trim the strings somewhere. \$\endgroup\$ – RobH Jul 12 '17 at 12:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.