How to map foreign keys using the POCO annotation CTP4 entity structure with an existing database

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

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 a free api if I need) to map a foreign key. OfflinePackageDocument.PackageID to OfflinePackage.PackageID

I am trying to use 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', which was specified with the value RelatedToAttribute.Property, cannot be found in the corresponding type 'OfflinePackage'.

PackageID is certainly a property off-line.

I can’t understand what I am doing wrong here.

+4
source share
1 answer

I figured out how to make this work.

First, there must be the PackageID int property in the OfflinePackageDocument class (this maps directly to the foreign key in the table). You can then add the "virtual OnlinePackage Package" property by specifying the recently added package identifier 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 .... } 
+1
source

All Articles