Thomas
Thomas

Reputation: 5998

Configuring EF code first without a foreign key

I have the following model:

public class Product
{
    public long Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Catalog> Matches { get; set; }
}

public class Catalog
{
    public long Id { get; set; }
    public string Title { get; set; }
}

Using Entity Framework code first I configure this using:

public DbSet<Product> Products { get; set; }
public DbSet<Catalog> Catalogs { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    // not rules setup yet
}

Currently when EF creates my database it creates a nullable foreign key in the Catalogs table called Product_Id. Is there a way to configure EF to not create any foreign key in the Catalog table?

The catalog table contains imported items from a catalog that should have no relation to the Products table. At run time a search query will be fired for each product and the result will be added to the catalog collection of the product object.

Upvotes: 1

Views: 258

Answers (1)

Slauma
Slauma

Reputation: 177163

For your purpose I would exclude the Matches collection from the model, either by data annotation...

public class Product
{
    public long Id { get; set; }
    public string Name { get; set; }
    [NotMapped]
    public virtual ICollection<Catalog> Matches { get; set; }
}

...or in Fluent code:

 modelBuilder.Entity<Product>()
             .Ignore(p => p.Matches);

Upvotes: 1

Related Questions