首先配置EF代码而不使用外键

时间:2011-07-01 16:57:52

标签: entity-framework-4.1 ef-code-first

我有以下型号:

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; }
}

首先使用Entity Framework代码我使用:

进行配置
public DbSet<Product> Products { get; set; }
public DbSet<Catalog> Catalogs { get; set; }

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

目前,当EF创建我的数据库时,它会在Catalogs表中创建一个名为Product_Id的可为空的外键。有没有办法配置EF不在Catalog表中创建任何外键?

目录表包含目录中与Products表无关的导入项。在运行时,将为每个产品触发搜索查询,并将结果添加到产品对象的目录集合中。

1 个答案:

答案 0 :(得分:1)

出于您的目的,我会通过数据注释从模型中排除Matches集合...

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

...或在Fluent代码中:

 modelBuilder.Entity<Product>()
             .Ignore(p => p.Matches);
相关问题