LFish
LFish

Reputation: 297

Save any new/changed entity respectively in Entity Framework

first, I was only trying to update a modified model. Lets say, we talk about "Article" as a model. The following method is implemented in a class called "Articles":

    public static void SaveArticle(Article article) 
    {
        if (article.Id == 0)
        {
            webEntities.Articles.Add(article);
        }
        else
        {
            webEntities.Articles.Attach(article);
            webEntities.Entry(article).State = EntityState.Modified;
        }

        webEntities.SaveChanges();
    }

So whenever I want to save an modified article in a controller action, I just have to call "Articles.SaveArticle(myArticle);", which works as expected.
So far so good but this means I would need to implement this redundantly for every model/entity.

Then I thought about something like a template-pattern. I.e. a class called "Entity" where "Article" inherits from "Entity".
Furthermore, a class called "Entities" contains a static method like this:

    public static void SaveEntity(Entity entity) 
    {
        if (Entity.Id == 0) // <-- Problem 1
        {
            webEntities.Entities.Add(entity); // <-- Problem 2
        }
        else
        {
            webEntities.Entities.Attach(entity); // <-- Problem 3
            webEntities.Entry(entity).State = EntityState.Modified; // <-- Problem 4
        }

        webEntities.SaveChanges();
    }

So I would not need to implement it redundantly but I don't know how to solve the problems mentioned in the code above. Do I think too complicated or what would be a best practice to my problem?

Thanks in advance!

Kind regards

Upvotes: 0

Views: 86

Answers (1)

Gert Arnold
Gert Arnold

Reputation: 109255

Use generics.

public static void Save<T>(T entity)
    where T : class
{
    webEntities.Set<T>().AddOrUpdate(entity);
    webEntities.SaveChanges();
}

AddOrUpdate is an extension method in System.Data.Entity.Migrations.

Upvotes: 1

Related Questions