Adding an object with a foreign key in Entity Framework

c# entity-framework sql-server

Question

I have 2 tables Jobs and Schedule

Jobs

JobId - int,PK, Identity
ScheduleId - int, FK
Title - varchar
Description - varchar

Schedules

ScheduleId - int,PK, Identity
Name - varchar

There is a relationship one to many with cascade on delete.

When I create Entity model, the generated Jobs model removes the ScheduleId field.

The Problem is that I can't Insert new Job with specified ScheduleId!

 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();

Note: I have a row in Schedules table with scheduleId=1.

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

Popular Answer

You can assign Schedule without actually loading Schedule object. Something 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);

I don't like this approach, case you have to hardcode entity types in string :/ If anyone know how to do this without such hardcoding - please comment.

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