Quantcast
Channel: ADO.NET, Entity Framework, LINQ to SQL, NHibernate
Viewing all articles
Browse latest Browse all 1698

Writing Parent and Child data at the same time.

$
0
0

Morning,

Hope someone can help with with this. I have two models:

    public class Parent
    {
        public int ParentID { get; set; }

        public string  Data { get; set; }

        public virtual ICollection<Child> Children { get; set; }
    }

    public class Child
    {
        public int ChildID { get; set; }
        public int ParentID { get; set; }

        public string Data { get; set; }

        public virtual Parent Parent { get; set; }
    }

What I would like to be able to do or know how to do is insert records into both in one hit. Something like the below:

        public async Task<IActionResult> CreateParent(Parent parent)
        {
            parent.Child.Add(new Child
            {
                Data = "SomeData"
            });

            _context.Add(parent);

            await _context.SaveChangesAsync();
        }

Obviously before the parent record is saved, I don't have the PK from the Parent table to put in the FK of the Child table and I believe that is why I am getting Object 'reference not set to an instance of an object.', but obviously I could be completely wrong.

I thought, wrong or right, it would potentially automagically add the FK as the insert would be as it would be a single Company object with a child contained.


Hope that makes sense and someone can help me out with this, cheers






Viewing all articles
Browse latest Browse all 1698

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>