example | C#, .NET, EntitySpaces | Testing whether an item is already in the database
Intent: Using the EntitySpaces ORM framework, test whether an item exists in a database or not. The example below shows a test of whether a "tag" appears in the database.
Overview: Write a function which accepts the item to test as a string parameter. Instantiate an EntityCollection. Execute an ES Query on that collection, using the Like operator and using the tag string as the parameter. Execute the ES .Load() method to load all available items into a collection. Run a comparison operation on whether Entity.Count is greater than or equal to one. If you wish to return a property of the found items, iterate over the EntityCollection using foreach, instantiating a single item within the collection on each loop. Return the property of the found item if you wish.
Discussion: Useful if you want to enforce single entries to a database table. The tags example below is a good application of this: you want to build a directory of categorical tags and list them only once, referencing the single tag many times using a Join table.
public int IsTagInDatabase(string tagToCheck)
{
TagsCollection tagcoll = new TagsCollection();
tagcoll.Query.Where(tagcoll.Query.Name.Like(tagToCheck.ToLower()));
tagcoll.Query.Load();
int tagID = 0;
if (tagcoll.Count >= 1)
{
foreach (Tags tag in tagcoll)
{
tagID = Convert.ToInt32(tag.Tagid);
}
return tagID;
}
else
{
return 0;
}
}

0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home