开发者

Get foreign key value in Entity Framework 1.0 without Include method

I'm using VS2008 (.NET 3.5) and Entity Framework over SQL Server. I'm hoping to get the value of a foreign key column without using the Include() method to link up the table.

For example, the simple Author has many Books sample.

var book = context.开发者_JS百科Books.First();
int authorId = book.Author.AuthorId;

In this scenario, an exception is thrown, because Author is null. I'm looking to just get the author ID, but don't need the rest of the Author object. There is no AuthorId property on the Book class.

I'm sure there's a way to do this, probably by editing the EDMX directly, or maybe through the designer - any ideas how to get started?

Thanks


You can get the FK value but it is not as straight forward. Each your navigation property representing single entity should have its pair property called XXXReference. In your case AuthorReference. This is the EF infrasturcture property holding your key internally. You can use similar code to get your FK value:

EntityKey key = book.AuthorReference.EntityKey;
EntityKeyMembers[] keyMembers = key.EnityKeyValues;
// Now each member of this array contains Key and Value property. Key is the name of 
// primary key property in principal entity and value is its value
// If you don't have composite keys and your keys are integer you can simply use:
int authorId = (int)keyMembers[0].Value;


I've seen this mentioned a few places, and it might be worth a look.

Extension method:

public static TValue GetId<TValue>(this EntityReference reference)
{
     if (reference == null)
     {
        return default(TValue);
     }

     EntityKey key = reference.EntityKey;
     if (key != null)
     {
         EntityKeyMember[] entityKeys = key.EntityKeyValues;
         if (entityKeys.Length > 0)
         {
            return (TValue)entityKeys[0].Value;
         }
     }

     return default(TValue);
}

In a partial class for your Book entity:

public int AuthorId
{
   get { return AuthorReference.GetId(); }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜