chuckd
chuckd

Reputation: 14520

Can't update child entity without going through parent in entity framework

I'm trying to update a child entity but there is a foreign key relationship that is created between the parent and the child. I've created a repository for the child entity and when I try to insert a child into the db without first pulling the parent the foreign key column is empty. Here is my scenario.

parent entity

public class YogaSpace
{
    public int YogaSpaceId { get; set; }
    //other members here
    public virtual ICollection<YogaSpaceEvent> Events { get; set; }
}

child entity

public class YogaSpaceEvent
{
    public int YogaSpaceEventId { get; set; }
    public string Title { get; set; }
    public DateTime DateTimeScheduled { get; set; }
    public int AppointmentLength { get; set; }
    public int StatusEnum { get; set; }
}

in the database table YogaSpaceEvent it creates a column called 'YogaSpace_YogaSpaceId' that hold the foreign key to the parents YogaSpace's id.

So now if I want to insert a new YogaSpaceEvent into the table directly using a newly created repo here.

//calling yogaspaceeventrepo to insert directly into child entity table
yogaSpaceEventRepository.Add(Convert.ToInt16(id), title, dateWithTime, Convert.ToInt16(duration));
yogaSpaceEventRepository.Save();

I don't have access, via c#, to add a value to 'YogaSpace_YogaSpaceId' so the column value is empty .

YogaSpaceEvent table enter image description here

I have to go and use my parent entity 'YogaSpace' repository and fetch a 'YogaSpace' and then add a new 'YogaSpaceEvent' to it. It's like two more steps and another fetch from the db but it works.

Is there another way to insert the 'YogaSpaceEvent' directly into the table without having to go through the parent entity 'YogaSpace'? Is there another way I can use code first attributes to do this, even though there is a foreign key relationship?

Upvotes: 0

Views: 805

Answers (2)

Praveen Paulose
Praveen Paulose

Reputation: 5771

public class YogaSpaceEvent
{
public int YogaSpaceEventId { get; set; }

public int YogaSpaceID { get; set;}
[ForeignKey("YogaSpaceID")]
public virtual YogaSpace YogaSpace {get; set;}

public string Title { get; set; }
public DateTime DateTimeScheduled { get; set; }
public int AppointmentLength { get; set; }
public int StatusEnum { get; set; }
}

Add a new property for the parent I'd and another property for the parent object. Mark the parent object as virtual and set the Foreign Key attribute

Upvotes: 1

Jeow Li Huan
Jeow Li Huan

Reputation: 3796

You can add the YogaSpace_YogaSpaceId property to YogaSpaceEvent so that you can manipulate the parent Id directly. Without mapping the foreign key, you'll have to fetch the parent entity.

Upvotes: 0

Related Questions