开发者

Extending DbContext to use generic Entry(...)

开发者 https://www.devze.com 2023-03-06 13:54 出处:网络
This isn\'t a question as much as its a crowd-sourced code review... I noticed you can use context.Entry(itemToModify) for adding objects as well as update & delete with one catch, itemToModify\'

This isn't a question as much as its a crowd-sourced code review...

I noticed you can use context.Entry(itemToModify) for adding objects as well as update & delete with one catch, itemToModify's type has to be specified, it can not be generic.

If I could get around the generic types issue, I could eliminate and simplify my code.

Here's what I did, it works locally, let me know what you think, if you see problems etc.开发者_如何转开发

public static class ExtensionMethods
{
    public static bool ModifyContext<T>(this DbContext context, T itemToModify, EntityState state) where T : class
    {
        // Function that throws a null arg exception 
        ValidationFunctions.IsNotNull(itemToModify);

        context.Entry(itemToModify).State = state;

        return context.SaveChanges() > 0;
    }
}

public class PersonRepository : IPersonRepository
{
    private readonly SomeContext _context = new SomeContext();

    /// <summary>
    /// Add a person
    /// </summary>
    public bool Add(Person personToAdd)
    {
        return _context.ModifyContext(personToAdd, EntityState.Added);
    }

    // Edit, Delete etc ...
}


I don't understand your code. Why do you use this:

 var type = itemToModify.GetType();
 var item = Convert.ChangeType(itemToModify, (Type)type);
 context.Entry(item).State = state;

When you have strongly typed entity?

Why not use just this:

context.Entry(itemToModify).State = state;

or

context.Entry<T>(itemToModify).State = state;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号