Adding an object with a foreign key in Entity Framework

c# entity-framework sql-server

Question

My tables are Jobs and Schedule.

Jobs

Identity, PK, and JobId
ScheduleId: FK, int
Input type: varchar
Character type: varchar

Schedules

ScheduleId is an int, PK, and identity.
the varchar name

With cascade on delete, there is a one to many connection.

The ScheduleId column is removed from the produced Jobs model when I construct an Entity model.

My inability to insert new jobs with provided ScheduleId is the issue!

 Job job = new Job();
 job.title= "blabla";
 job.description="xyz";
 job.scheduleId=1// can't have this!

 if (job.EntityState == EntityState.Detached)
 {
      myContext.AddToJobs(job);
 }
 myContext.SaveChanges();

I have an entry in the Schedules database with the identifier scheduleId=1.

1
3
8/12/2010 3:15:33 PM

Popular Answer

Without actually loading the Schedule object, you may allocate the Schedule. Possibly like this:

db = new OneToManyEntities(); 
var address = new Address { Address1 = "Oakumber st", City = "Dallas", State = "Tx", Zip = "76111" }; 
address.CustomerReference.EntityKey = new EntityKey("OneToManyEntities.Customer","CustomerId",2); 
db.AddToAddresses(address);

This method, if you have to hardcode entity types in a string, is not something I appreciate. Please leave a comment if you know how to achieve this without using such hardcoding.

1
8/13/2010 9:40:30 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow