EF5代码首先在DbSet查询上执行意外的JOIN

时间:2013-07-19 10:15:08

标签: entity-framework ef-code-first sql-view

在尝试编写一些干净的模型类库时,我使用的是EF5 Code First。使用EntityTypeConfiguration,各种属性将映射到SQL Server 2005服务器实例上托管的2个VIEWS的列。

小心:我知道有一些糟糕的表列命名正在进行,但我必须处理这个,因为它是一个现有的数据库。请原谅我。

完成管道工程后,我可以查询客户帐户...

var context = new Data.EntityContext();
public IQueryable<ClientAccount> GetClients(List<string> usernameOrEmail)
{
    return context.ClientAccount.Where(p => usernameOrEmail.Contains(p.UserName) || usernameOrEmail.Contains(p.Email)).Include("Company").AsQueryable();
}

...返回匹配的客户,包括公司详细信息。

但是,在尝试仅获取公司列表时,结果包含大量重复项。

var companies = data.Companies.Where(c => c.IsActive).OrderBy(c => c.Name);

使用SQL Server Profiler我发现,由于我不清楚的原因,引擎会提供LEFT OUTER JOIN以便包含客户端的userId:

SELECT 
    [Extent1].[Id] AS [Id], 
    [Extent1].[Company] AS [Company], 
    [Extent1].[Address] AS [Address], 
    [Extent1].[AddressSuffix] AS [AddressSuffix], 
    [Extent1].[Zip] AS [Zip], 
    [Extent1].[City] AS [City], 
    [Extent1].[State] AS [State], 
    [Extent1].[CountryName] AS [CountryName], 
    [Extent1].[Telephone] AS [Telephone], 
    [Extent1].[Fax] AS [Fax], 
    [Extent1].[Url] AS [Url], 
    [Extent1].[Latitude] AS [Latitude], 
    [Extent1].[Longitude] AS [Longitude], 
    [Extent1].[isPublic] AS [isPublic], 
    [Extent1].[active] AS [active], 
    [Extent1].[parent] AS [parent], 
    [Extent2].[userId] AS [userId]
FROM  [dbo].[VIEW_CompaniesCountryContinent] AS [Extent1]
    LEFT OUTER JOIN [dbo].[PassportAccounts] AS [Extent2] ON ([Extent2].[companyId] IS NOT NULL) AND ([Extent1].[Id] = [Extent2].[companyId])
WHERE 1 = [Extent1].[active]

我很困惑,因为我没有从公司模型链接到客户。 VIEW不包括用户表,只针对公司表。

很明显,我错过了一些东西,我希望你能让我回到正轨。 您将在下面找到有关模型,上下文和实体配置的一些详细信息。 谢谢!

代码信息:

模型相当简单......

public class ClientAccount : IUserAccount
{
    public ClientAccount() { }

    [Key]
    public int ClientId { get; set; }

    [DisplayName("User Name")]
    public string UserName { get; set; }

    [DisplayName("First Name")]
    public string FirstName { get; set; }

    [DisplayName("Last Name")]
    public string LastName { get; set; }

    [DisplayName("Job Title")]
    public string JobTitle { get; set; }

    [DisplayName("Company")]
    public virtual Company Company { get; set; }

    [DisplayName("Direct Phone")]
    public string PhoneDirect { get; set; }

    [DisplayName("Mobile phone")]
    public string PhoneMobile { get; set; }

    [DisplayName("Registration Date")]
    public DateTime DateRegistered { get; set; }

    [DisplayName("Last Login")]
    public DateTime LastLogin { get; set; }

    [EmailAddress]
    [DisplayName("Email")]
    public string Email { get;set; }

    public bool IsApproved { get; set; }
    public bool IsActive { get; set; }
    public bool IsLockedOut { get { return !IsActive; } }
    public bool IsOnline
    {
        get { return (LastLogin.AddMinutes(10) > DateTime.Now); }
    }

    public DateTime LastActivityAt  {   get; set; }
}

public class Company
{
    [Key]
    public int ID { get; set; }

    public string Name { get; set; }

    public string Address { get; set; }
    public string Address2 { get; set; }

    public string Zip { get; set; }
    public string City { get; set; }
    public string State { get; set; }

    public string Country { get; set; }

    public string Telephone { get; set; }
    public string Fax { get; set; }
    public string Url { get; set; }

    public string TimeZone { get; set; }
    public Coordinate Coordinate { get; set; }

    public bool IsPublic { get; set; }
    public bool IsActive { get; set; }

    public int ParentCompanyId { get; set; }

}

public class Coordinate
{       
    public decimal? Latitude { get; set; }
    public decimal? Longitude { get; set; }
}

到目前为止没什么特别的(对吗?)。 DbContext

public class EntityContext : DbContext
{

    public EntityContext() : base("Name=EntityContext")
    {
        Database.SetInitializer<EntityContext>(null);
    }

    public EntityContext(string connectionString)
        : base(connectionString)
    {
        Database.SetInitializer<EntityContext>(null);
    }

    public DbSet<ClientAccount> ClientAccount { get; set; }
    public DbSet<Company> Companies { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new CompanyConfiguration());
        modelBuilder.Configurations.Add(new ClientAccountConfiguration());

        base.OnModelCreating(modelBuilder);
    }
}

EntityTypeConfigurations ...

public class ClientAccountConfiguration : EntityTypeConfiguration<ClientAccount>
{
    public ClientAccountConfiguration()
        : base()
    {
        HasKey(p => p.ClientId);

        ToTable("ClientAccounts"); // VIEW ClientAccounts

        Property(p => p.ClientId)
            .HasColumnName("userId")
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
            .IsRequired();

        Property(p => p.Email)
            .HasColumnName("userEmail")
            .IsRequired();

        Property(p => p.UserName)
            .HasColumnName("userLogin")
            .IsRequired();

        Property(p => p.FirstName).HasColumnName("userFirstName");
        Property(p => p.LastName).HasColumnName("userLastName");
        Property(p => p.PhoneDirect).HasColumnName("userPhoneDirect");
        Property(p => p.PhoneMobile).HasColumnName("userPhoneMobile");

        Property(p => p.JobTitle)
            .HasColumnName("userPosition");

        HasOptional(p => p.Company)
            .WithOptionalDependent()
            .Map(p => p.MapKey("companyId"));

        Property(p => p.IsApproved).HasColumnName("Employed");
        Property(p => p.IsActive).HasColumnName("active");
        Property(p => p.LastActivityAt).HasColumnName("updated");
        Property(p => p.LastLogin).HasColumnName("LastLogin").IsOptional();
        Property(p => p.DateRegistered).HasColumnName("created");

    }
}

public class CompanyConfiguration : EntityTypeConfiguration<Company>
{
    public CompanyConfiguration()
    {
        this.HasKey(c => c.ID);


        this.ToTable("VIEW_CompaniesCountryContinent");
        this.Property(c => c.ID)
            .HasColumnName("Id")
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

        this.Property(c => c.Name)
            .HasColumnName("Company")
            .IsRequired();

        this.Property(c => c.Address).HasColumnName("Address");
        this.Property(c => c.Address2).HasColumnName("AddressSuffix");
        this.Property(c => c.Country).HasColumnName("CountryName");
        this.Property(c => c.City).HasColumnName("City");

        this.Property(c => c.Zip).HasColumnName("Zip");
        this.Property(c => c.State).HasColumnName("State");

        this.Property(c => c.Coordinate.Latitude).HasColumnName("Latitude");
        this.Property(c => c.Coordinate.Longitude).HasColumnName("Longitude");

        this.Property(c => c.TimeZone).HasColumnName("timezone");

        this.Property(c => c.IsPublic).HasColumnName("isPublic");
        this.Property(c => c.IsActive).HasColumnName("active");

        this.Property(c => c.ParentCompanyId).HasColumnName("parent");

    }
}

1 个答案:

答案 0 :(得分:0)

跟进Aron提供的解决方案。

实施此修复程序后,我很快遇到了无法更新ClientAccount对象公司的问题。这是有道理的,因为模型不允许更新ClientAccount对象的CompanyId属性。

外键属性已包含在模型中,其次,属性名称必须与其指向的对象的键属性名称相匹配。这也解决了我原来的问题。 它确实需要更改(现有的)公司模型,这将对已经使用公司类的其他项目产生影响。

更改:

在我的模型中,我添加了CompanyId属性,并将Company id属性的名称从ID更改为CompanyId(为了匹配两个属性名称):

public class ClientAccount : IUserAccount
{
    public ClientAccount() { }

    ...

    public Nullable<int> CompanyId { get; set; }

    [DisplayName("Company")]
    public virtual Company Company { get; set; }

    ...
}

public class Company
{
    [Key]
    public int CompanyId { get; set; }

    public string Name { get; set; }

    ...

}

在EntityTypeConfiguration中,我将新的CompanyId属性映射到相应的数据库列名,并且可以省略公司映射。

public class ClientAccountConfiguration : EntityTypeConfiguration<ClientAccount>
{
    public ClientAccountConfiguration()
        : base()
    {
        ...

        Property(p => p.CompanyId).HasColumnName("companyId");

        /*
        HasOptional(p => p.Company)
            .WithOptionalDependent()
            .Map(p => p.MapKey("companyId"));
        */

        ...
    }
}