Dynamically calling field

  • Thread starter Thread starter Cowboy \(Gregory A. Beamer\)
  • Start date Start date
C

Cowboy \(Gregory A. Beamer\)

I am going on a search tonight for this, but figured I would throw it out
here as my brain is mush right now.

Have a nearly full generic implementation of a LINQ to SQL Repository
(inspired by quite a few examples I have seen out there). Now I am down ot
the Delete function, which takes a LINQ to SQL object and fires off a
logical delete if a particular field is there.

I know there are ways to accomplish this by altering the classes or adding a
partial class for each class. The issue here is I don't really want to incur
the time to add partial classes to the LINQ to SQL class and I want to be
able to regenerate the LINQ to SQL classes if I alter the schema, so neither
dinking with the generated source (always a mess) or adding partial classes
are particularly appealing.

I might also be able to do so through an extension method on the LINQ
classes. I am not against this method of solving the problem either.

Most of the fields in the database have an IsDeleted bit field. If this
field is present in the LINQ to SQL object, I want to set it to 1 (true) and
save the object rather than actually delete from the database.

A coworker suggested adding a static method that casts to the proper type:

switch(entity.GetType())
{
}

Yes, this can be done, but it is a maintenance nightmare.

Any clever ideas?

--
Gregory A. Beamer
MVP, MCP: +I, SE, SD, DBA

Subscribe to my blog
http://feeds.feedburner.com/GregoryBeamer#

or just read it:
http://feeds.feedburner.com/GregoryBeamer

********************************************
| Think outside the box! |
********************************************
 
Wrong group. Should be in C#. Found a solution regardless:

public void Delete(T entity)
{
Type type = entity.GetType();
string property = "IsDeleted";

PropertyInfo propertyInfo = type.GetProperty(property);

if (propertyInfo == null)
{
Destroy(entity);
}
else
{
using (System.Data.Linq.DataContext context =
_dataContextFactory.Context)
{
Table<T> table = context.GetTable<T>();
//TODO: Figure out why .Attach() is not working and stop
grabbing object
entity = table.First(s => s == entity);

MethodInfo methodInfo = propertyInfo.GetSetMethod();
object[] o = { true };
methodInfo.Invoke(entity, o);

context.SubmitChanges();
}
}
}

--
Gregory A. Beamer
MVP, MCP: +I, SE, SD, DBA

Subscribe to my blog
http://feeds.feedburner.com/GregoryBeamer#

or just read it:
http://feeds.feedburner.com/GregoryBeamer

********************************************
| Think outside the box! |
********************************************
 
Back
Top