Dynamically calling field

  • Thread starter Cowboy \(Gregory A. Beamer\)
  • 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?
 
C

Cowboy \(Gregory A. Beamer\)

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();
}
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top