Asked by:
C# WinForms - Saving to database via Entity

Question
-
Hey!
I'm building some sort of customer management program and am running aground currently. I have two tables, 'customers' and 'contacts'. In my WinForm I have 2 textboxes and 1 combobox. The textboxes will have the values Name and FirstName for the table contacts respectively and the combobox selects 1 customer from the customers table and I need the ID of that customer to be inserted into contacts aswell. What is the smartest way to do this? I've been trying different things for quite some time now and have not gotten anywhere.
- Moved by CoolDadTx Tuesday, April 17, 2018 1:54 PM EF related
Tuesday, April 17, 2018 11:47 AM
All replies
-
Hello,
Please indicate either in words or code what you have tried and how you created your entities.
Also what version of EF is being used.
Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
VB Forums - moderator
Tuesday, April 17, 2018 1:02 PM -
In fact it is easy, you need to do SaveChanges
https://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext.savechanges(v=vs.113).aspx
The documentation around this is really unmicrosoft.
Success
CorTuesday, April 17, 2018 1:19 PM -
Hi Hootcake,
According to your description, if you use entity framework, which is a one-to-many relationship, one contact has many customers, which model will be like below:
public class Contract { public int ContractId { get; set; } public string Address { get; set; } public virtual ICollection<Customer> Customers { get; set; } public Contract() { Customers = new Collection<Customer>(); } } public class Customer { public int Id { get; set; } public string CustomerName { get; set; } // foreign key of Contract table public int ContractId { get; set; } public virtual Contract Contract {get; set;} }
If you want to insert a customer into database, please try the following code.
using (var db = new EFDemoContext()) { Customer custom = new Customer(); custom.Id = 1; custom.CustomerName = "Test"; custom.ContractId = //From your combobox's value
db.Customers.Add(custom); db.SaveChanges(); }
Best regards,
Zhanglong
MSDN Community Support
Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.- Proposed as answer by Zhanglong WuMicrosoft contingent staff Thursday, April 19, 2018 1:23 AM
Wednesday, April 18, 2018 1:39 AM