开发者

How to map foreign keys using entity framework CTP4 POCO annotations with an existing database

I have an existing DB with a very simple one-way foreign key relationship between two tables. I need to create classes with mappings that will work with the existing DB.

CREATE TABLE OfflinePackage (
      PackageID int,
      Name nvarchar(100)
      ...

CREATE TABLE OfflinePackageDocument (
      PackageDocumentID int,
      P开发者_StackOverflow中文版ackageID int,  --- FK references OfflinePackage.PackageID
      ...

I define a class for each of these tables. I want to use annotations (or fluent api if I have to) to map the foreign key OfflinePackageDocument.PackageID to OfflinePackage.PackageID

I'm trying to use the RelatedTo annotation:

public class OfflinePackageDocument
{
      [Key, StoreGenerated(StoreGeneratedPattern.Identity)]
      public int PackageDocumentID { get; set; }

      [RelatedTo(Property = "PackageID")]
      public virtual OfflinePackage Package { get; set; }

      ...

}

public class OfflinePackage
{
    [Key, StoreGenerated(StoreGeneratedPattern.Identity)]
    public int PackageID { get; set; }

    ...
}

But I get this error during ModelBuilder.CreateModel():

The navigation property 'PackageID' that was specified by the RelatedToAttribute.Property value cannot be found on the related type 'OfflinePackage'.

PackageID certainly is a property in OfflinePackage.

I can't figure out what I'm doing wrong here.


I figured out how to make this work.

First, there must be a PackageID int property in the OfflinePackageDocument class (this maps directly to the foreign key in the table). Then, you can add the "virtual OfflinePackage Package" navigation property, indicating the newly added PackageID as a foreign key.

public class OfflinePackageDocument
{
    [Key, StoreGenerated(StoreGeneratedPattern.Identity)]
    public int PackageDocumentID { get; set; }

    public int PackageID { get; set; } // This must exist - maps directly to the DB field

    [RelatedTo(ForeignKey = "PackageID")]
    public virtual OfflinePackage Package { get; set; } // Now we can define this navigation property

    ....
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜