AddOrUpdate in Entity Framework 7
<p>I'm trying to implement my own <code>AddOrUpdate</code> since Entity Framework doesn't contain this function for now. (And I need it)</p>

<p>I know there are similar questions here, but either there's no answer or it was another problem.</p>

<p>So, I'm stuck when trying to implement the update-part. This is my code:</p>

<ul>
<li>@this: my DbSet of entries in the Database</li>
<li>parameter: the attribute to check in the DB whether to entry already exists</li>
<li>entries: all entries to either add or update</li>
</ul>

<hr>

<pre><code>public static void AddOrUpdate&lt;T&gt;(this DbSet&lt;T&gt; @this, Func&lt;T, object&gt; parameter, params T[] entries) where T: class, IEntity
{
    IEnumerable&lt;object&gt; keysExisting = @this.Select(parameter);

    foreach (T entry in entries)
    {
        bool entryExistsAlready = keysExisting.Contains(parameter.Invoke(entry));
        if (!entryExistsAlready)
        {
            @this.Add(entry);
            return;
        }
        entry.Id = @this.First(w =&gt; parameter.Invoke(w).Equals(parameter.Invoke(entry))).Id;
        @this.Attach(entry);
        @this.Update(entry);
    }
}
</code></pre>

<p>and for completing the information, this is how I call the method (There's already an ApplicationUser stored in the DB, with the Email "test@test.de"):</p>

<pre><code>db.ApplicationUsers.AddOrUpdate(s =&gt; s.Email,
        new ApplicationUser{Email="test@test.de", Attribute="modified attribute"}
        );
</code></pre>

<p>I tried with attaching the entry and without attaching. I'm always getting following exception (either on <code>Attach()</code> or, when don't attaching, on <code>Update()</code>: </p>

<blockquote>
  <p>InvalidOperationException: The instance of entity type 'ApplicationUser' cannot be tracked because another instance of this type with the same key is already being tracked. When adding new entities, for most key types a unique temporary key value will be created if no key is set (i.e. if the key property is assigned the default value for its type). If you are explicitly setting key values for new entities, ensure they do not collide with existing entities or temporary values generated for other new entities. When attaching existing entities, ensure that only one entity instance with a given key value is attached to the context.</p>
</blockquote>

<p>Any idea, how I can update my entries? </p>

<p><strong>update:</strong></p>

<p>I already tried with reflection, just setting all values from each property, but ApplicationUser e.g. has the property <code>Role</code> which is not writeable. So I'd lose data from my method-call.</p>