0

I have a following database structure.

enter image description here

I have already saved Buyer in database. I have buyer id. I have to save contact information of a buyer in the database, as I save contact in the database I also need to save buyercontact in buyercontact table. When I try to add BuyerContact table in the edmx file, Visual Studio 2010 won't allow me to do that.

How do I save information in buyercontact table? Please help.

They say if appropriate relationship is maintained in the database/edmx, buyercontact will be saved to database as well when i cave "contact". I search through the internet, i also found similar questions asked but i could not understand.

Please help. do i have to write some special code to save BuyerContact

When I write this code to save contact along with buyercontact, I get error

Cannot insert duplicate key in dbo.Buyer

Contact objContact = new Contact();
objContact.FirstName = firstName;
objContact.MiddleName = middleName;
objContact.Lastname = lastName;
objContact.CreatedDate = DateTime.Now;
objContact.AddressId = gAddressId;                    

var buyer = _buyerRepository.GetSingle(x => x.BuyerId == BuyerID);
objContact.Buyer = buyer;

_contactRepository.Add(objContact);
_contactRepository.Save()

If I remove objContact.Buyer = buyer;, then contact information is saved successfully but buyercontact is not saved. Now my problem is as soon as I have contact associated with the buyer I also need to save it in the BuyerContact table.

I have already been through post here, but O could not understand. I have used generic Linq-to-SQL repository for common database operations like CRUD.

Please help, thanks

Community
  • 1
  • 1
NCCSBIM071
  • 1,207
  • 1
  • 16
  • 30

1 Answers1

0

try this, instead of:

objContact.Buyer = buyer;
_contactRepository.Add(objContact);
_contactRepository.Save()

replace with:

buyer.Contacts.Add(objContact);
_buyerRepository.Save();

also assuming you are using same context object across all repositories for unit of work

Kris Ivanov
  • 10,476
  • 1
  • 24
  • 35