0

Using Entity Framework Core I want to reuse the same object for multiple database Users.

Entity framework core database models with one to one relation:

public class User {

   public int UserId {get;set;}

   ...

   public virtual UserData {get;set;}
}
public class UserData {

   public int UserDataId {get;set;}

   ...

   public int UserId {get;set;}

   [ForeignKey("UserId")]
   public virtual User User {get;set;}
}
_userData = ... 

_user = new List<User> 
{ 
   new User { 
      UserData = _userData,
      ...
   },
   new User {
      UserData = _userData,
      ...
   }
}

_context.User.AddRange(_user);

If I try to add the same UserData object twice the second one is ignored. If I clone the UserData object first (by implementing ICloneable) EF can insert the redundant UserData as desired.

Is there a smarter way without ICloneable?

The context:

public class MyDbContext : DbContext
{
   public DbSet<User> User {get;set;}
   
   public DbSet<UserData> UserData {get;set;}

   ...
}
Icad
  • 101
  • 1
  • 6
  • 1
    Nope, EF tracks entities by reference. So make copy. Also you can use [Automapper](https://stackoverflow.com/questions/5713556/copy-object-to-object-with-automapper) for such task. – Svyatoslav Danyliv Dec 21 '21 at 12:55
  • 1
    `UserData` is e reference type i.e. `_userData` will point to the same object. If you don't clone it, EF will thus take that object, set the ID and the next entry will be the database object. If you want multiple `User` to have the same `UserData`, a 1-to-1 relation will not work. You'll need a one-to-many. E.g. You can setup a `UserData` to have a virtual list of `User`s with a reverse dependency. If you want 1-to-1, you need to clone. – JHBonarius Dec 21 '21 at 12:55

0 Answers0