0

How can i Insert record into multiple tables using Linq?

I have three related tables Contact, Phone and Email, Is it possible to create Contact first then Phone or Email. Since Phone and Email use ContactID as a foreign Key

Here is my linq expression looks like:

 var Contact = Mapper.Map<Contact>(request.CreateContactInformation);
    Contact.CreatedBy = request.CreateContactInformation.CreatedBy;
    Contact.CreatedDate = SystemClock.UtcNow;
    Contact.UpdatedBy = request.CreateContactInformation.UpdatedBy;
    Contact.UpdatedDate = SystemClock.UtcNow;

    await Context.AddAsync(Contact);
    await Context.SaveChangesAsync();

    var phones = Mapper.Map<Phone>(request.CreateContactInformation);
    phones.ContactID = Contact.ID;
    phones.PhoneNumber = request.CreateContactInformation.PhoneNumber;     
    Context.AddAsync(phones);
    await Context.SaveChangesAsync();


    var email = Mapper.Map<Email>(request.CreateContactInformation);
    email.ContactID = Contact.ID;
    email.EmailAddress = request.CreateContactInformation.Email;
    Context.AddAsync(email);
    await Context.SaveChangesAsync();

But i get this exception error

InternalServerError. Error Content: System.ArgumentException: Cannot create an instance of abstract type ....EF.Base.BaseEntity. (Parameter 'type') at ...AsyncTransactionInterceptor.InterceptAsync[T](Task`1 task, String methodName)

2
  • Look like we need more detail about your model to resolve the problem.If there're some abstract method in the model. Commented May 25, 2020 at 5:06
  • Please share your model and the mapped model. Commented May 26, 2020 at 9:19

1 Answer 1

0

I am not very sure about what your context actually is. But I guess your Add function might look like :

  await Context.Contact.AddAsync(Contact);

Since you are not specifying which table to insert. And in other AddAsync() function , you need to enclose it by await. Or it'll still be a Task , and will not be invoked.

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

1 Comment

Thank you Talesa!, i tried that still gives me the same error

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.