开发者

Linq-to-SQL: foreign key not accessible until transaction is committed

I've found that with Linq-to-SQL, when you create a new object you can not access a foreign-key member until you have called SubmitChanges on the context the new object is being "created with." I understand, of course, that the FK doesn't really exist until you've committed the new object to the database - but it seems that the information is there to allow the lookup to work. Take, for example, the code below.

public Course Create(string name, int teacherID)
{
     using (MyDataContext context = new MyDataContext())
    {
        Course c = new Course();

        c.Name = name;
        c.TeacherID = 开发者_运维问答teacherID; //FK here, assume the value references a valid Teacher.
        context.Courses.InsertOnSubmit(c); //c now has a context it can use.

        //Try to do some validation here, before commiting the Course to the database.
        //c.Teacher will be null here, leading to an exception.
        if (c.Teacher.FirstName.Equals("Phil"))
            throw new ApplicationException("Phil quit last year."); //Throwing here would cause the transaction to never commit, good.

        context.SubmitChanges();

        //Email the teacher.
        SendEmail(c.Teacher.EmailAddress); //c.Teacher is no longer null, this would work fine.
    }
}

The above code has some comments that should illustrate what I'm asking. My question is basically this:

Why must I first SubmitChanges in order to lookup a value based on a primitive ID (FK) which is already set on the object?


Yes, c.Teacher would be null there. Linq-To-Sql does not provide any mechanism to load an entity based on a manually populated foreign-key column (at least, not until you get to SubmitChanges). Certainly it would lazy-load if you had pulled the entity from the db -- but here you are creating it. Either pass in the teacher entity (instead of the id) or manually fetch the entity and set that instead:

c.Teacher = teacher

Instead of

c.TeacherID = teacherID
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜