2

I need to add many entities at once. This is not complex:

EntityType entities = GetEntities();
dbContext.MyTable.AddRange(entities);

However each entity references another sub property (that is already existing, and for which I know the id). Is there an efficient way to avoid querying in advance all the subproperties?

for (int i = 0; i < entities.Length; i++)
{
    // adding already existing property 
    entities[i].MyProperty = new MyProperty { Id = ExternalIds[i] };
}

dbContext.MyTable.AddRange(entities); // Don't want to create new entities

2 Answers 2

3

You can create the empty entity object with just the id, you could also add the property key to your entity

public class Course
{
  public int CourseID { get; set; }
  public string Title { get; set; }
  public int Credits { get; set; }
  public int DepartmentID { get; set; }
  public virtual Department Department { get; set; }
}

Here, you could just put the DepartmentID value and save, or

Course.Department = new Department{ id = 123 }

The docs says

If the reference is in the added state (in this example, the course object), the reference navigation property will not be synchronized with the key values of a new object until SaveChanges is called.

Sign up to request clarification or add additional context in comments.

Comments

0

Two solutions, first you can attach the related entity object manually so that it is tracked in the unchanged state prior to adding the target entity object:

var myProps = ExternalIds
    .Select( id => new MyProperty { Id = id } )
    .ToArray();

dbContext.AttachRange( myProps ); // tracks as Unchanged

...
entities[ i ].MyProperty = myProps[i];

Or expose the FK property for the nav property and simply set the ID (which is my preferred solution if you're working with the FK values)

public class EntityType
{
    ...
    public int MyPropertyId { get; set; }
    [ForeignKey( "MyPropertyId" )]
    public MyProperty MyProperty { get; set; }
}

...
Entities[i].MyPropertyId = ExternalIds[i]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.