简体   繁体   中英

Accessing ForeignKey field after creating entity in Entity Framework

When creating a new entity, if I try to access one of the foreign key fields immediately after creation, I'm getting an object reference exception. Here's the code -

        Call call = new Call()
        {
            ....
            StoreID = storeID,    //foreign key of store
            ....
        }
        db.Calls.Add(call);
        db.SaveChanges();
        ....

        // do something with store
        call.Store.Anything();

This throws:

Object reference not set to an instance of an object.

Because call.Store is not mapped to any object

Note that the code works perfectly if I don't try to access the Store object. If I redirect the user and the call is loaded from scratch, then accessing the Store object works no problem.

As a nasty hack I tried

 db.Entry(call).Reload();

but even that didn't help

How can I make the store object immediately accessible upon creation?


The model:

[Table("CALL_LOG")]
public class Call
{
    .....

    [Column("STORE_IID"), Required]
    public int StoreID { get; set; }

    [ForeignKey("StoreID")]
    public virtual Store Store { get; set; }

    .....
 }

The following will work I believe:

db.Entry<Call>(call).Reference("Store").Load()

This will tell it to load the Store navigation property.

Ok, now that I see more code that makes sense. Since you are storing the ID, you need to hit the database again to inflate the object.

Call call = new Call()
{

    ....

    StoreID = storeID,    //foreign key of store

    ....

}

db.Calls.Add(call);

db.SaveChanges();
call = db.Calls.Single(c => c.CallId = call.CallId).Include(c => c.Store);

....

// do something with store

call.Store.Anything();

If I get you right: 1. you are creating new Call-instance somehow not using db (with call = new Call() ?) instance before adding it with this line:

db.Calls.Add(call);

2. You get a NullReferenceException after trying to access the Store property.

If that's the case, adding a ctor, which will initialize Store, to Call class may help.

public Call()
{
 ...
    this.Store = new Store();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM