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
1 Answer 1
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.
-
\$\begingroup\$ I used
Trim()
beacse I don't want to saveTag name
with spaces around it , Like thisC#
or ` MVC ` \$\endgroup\$work question– work question2017年07月12日 10:20:08 +00:00Commented Jul 12, 2017 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– t3chb0t2017年07月12日 10:22:36 +00:00Commented Jul 12, 2017 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
Trim
ming incoming values is a better choice (but that's up for debate!) \$\endgroup\$RobH– RobH2017年07月12日 10:47:40 +00:00Commented Jul 12, 2017 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– t3chb0t2017年07月12日 10:59:31 +00:00Commented Jul 12, 2017 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– RobH2017年07月12日 12:48:44 +00:00Commented Jul 12, 2017 at 12:48
Explore related questions
See similar questions with these tags.