Take the 2-minute tour ×

I am using Entity Framework and Code First to map to a legacy database (I know that if I have the database already built then I should the "Database First" approach, but some how, I fill better putting the annotations by hand than handling control over the designer), in which, there is a table that have a key that point to another table (it is actually a synonym to a table in another db) that works like a foreign key but it not actually defined in the table schema.

The question is: can I force this relation to exist in my POCO classes? can I map this using the Fluent API? is this possible at all?

As usual, thanks in advance!

share|improve this question
add comment

1 Answer

up vote 0 down vote accepted

Sure, you can manually define a foreign key and navigation properties either by fluent mapping or data annotations.

Let's say I have a Parent table with a field CatCode and a synonym CategoryEx that points to a table Category in a second database. Both have corresponding classes and DbSets in one context. The mappings (derived from EntityTypeConfiguration) could look like (the constructors):

public ParentMap()
    this.HasKey(t => t.Id);
    this.HasRequired(p => p.Category).WithMany().HasForeignKey(p => p.CatCode);

public CategoryMap()
    this.HasKey(t => t.CatCode);

where Parent looks like:

public class Parent
    public int Id { get; set; }
    public string Name { get; set; }
    public string CatCode { get; set; }
    public Category Category { get; set; }
share|improve this answer
add comment

Your Answer


