C# WinForms - Saving to database via Entity RRS feed

  • 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
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Tuesday, April 17, 2018 1:02 PM
  • In fact it is easy, you need to do SaveChanges


    The documentation around this is really unmicrosoft. 


    Tuesday, 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,


    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.

    Wednesday, April 18, 2018 1:39 AM