views:

316

answers:

1

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,
      PackageID 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.

+1  A: 

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

    ....
}
ryanman
thanks i was just banging my head on this. i was getting duplicate columns on multiple foreign keys that map back to the same object... for instance CreatedBy, ModifiedBy both mapping back to the User object was giving me 2 columns for each. This fixed it
Eric Brown