簡體   English   中英

實體框架生成的查詢不存在列

[英]Entity framework generated query with not-exists column

有一張桌子

CREATE TABLE AppUserInRole
(
    Id              BIGINT          NOT NULL    IDENTITY PRIMARY KEY,                       
    IdAppUser       BIGINT          NOT NULL    FOREIGN KEY REFERENCES AppUser (Id),        
    IdAppUserRole   BIGINT          NOT NULL    FOREIGN KEY REFERENCES AppUserRole (Id),
    ValidFrom       DATETIME2       NOT NULL    DEFAULT GETDATE(),                          
    ValidTo         DATETIME2       NULL,                                                   
    CreatedDate     DATETIME2       NOT NULL    DEFAULT GETDATE(),                          
    CreatedBy       BIGINT  NULL FOREIGN KEY REFERENCES AppUser (Id),                                               
)

為了生成我,請使用EntityFramework反向POCO生成器( http://www.reversepoco.com/ )。

這是我的課程:

[Table("AppUserInRole", Schema = "dbo")]
[System.CodeDom.Compiler.GeneratedCode("EF.Reverse.POCO.Generator", "2.31.1.0")]
public partial class AppUserInRole
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Column(@"Id", Order = 1, TypeName = "bigint")]
    [Required]
    [Key]
    [Display(Name = "Id")]
    public long Id { get; set; } // Id (Primary key)

    [Column(@"IdAppUser", Order = 2, TypeName = "bigint")]
    [Required]
    [Display(Name = "Id app user")]
    public long IdAppUser { get; set; } // IdAppUser

    [Column(@"IdAppUserRole", Order = 3, TypeName = "bigint")]
    [Required]
    [Display(Name = "Id app user role")]
    public long IdAppUserRole { get; set; } // IdAppUserRole

    [Column(@"ValidFrom", Order = 4, TypeName = "datetime2")]
    [Required]
    [Display(Name = "Valid from")]
    public System.DateTime ValidFrom { get; set; } = System.DateTime.Now; // ValidFrom

    [Column(@"ValidTo", Order = 5, TypeName = "datetime2")]
    [Display(Name = "Valid to")]
    public System.DateTime? ValidTo { get; set; } // ValidTo

    [Column(@"CreatedDate", Order = 6, TypeName = "datetime2")]
    [Required]
    [Display(Name = "Created date")]
    public System.DateTime CreatedDate { get; set; } = System.DateTime.Now; // CreatedDate

    [Column(@"CreatedBy", Order = 7, TypeName = "bigint")]
    [Required]
    [Display(Name = "Created by")]
    public long CreatedBy { get; set; } // CreatedBy

    // Foreign keys

    /// <summary>
    /// Parent AppUser pointed by [AppUserInRole].([CreatedBy]) (FK__AppUserIn__Creat__1AD3FDA4)
    /// </summary>
    [ForeignKey("CreatedBy")] public virtual AppUser AppUser_CreatedBy { get; set; } // FK__AppUserIn__Creat__1AD3FDA4
    /// <summary>
    /// Parent AppUser pointed by [AppUserInRole].([IdAppUser]) (FK__AppUserIn__IdApp__30F848ED)
    /// </summary>
    [ForeignKey("IdAppUser")] public virtual AppUser AppUser_IdAppUser { get; set; } // FK__AppUserIn__IdApp__30F848ED
    /// <summary>
    /// Parent AppUserRole pointed by [AppUserInRole].([IdAppUserRole]) (FK__AppUserIn__IdApp__31EC6D26)
    /// </summary>
    [ForeignKey("IdAppUserRole")] public virtual AppUserRole AppUserRole { get; set; } // FK__AppUserIn__IdApp__31EC6D26
}

[System.CodeDom.Compiler.GeneratedCode("EF.Reverse.POCO.Generator", "2.31.1.0")]
    public partial class AppUserInRoleConfiguration : System.Data.Entity.ModelConfiguration.EntityTypeConfiguration<AppUserInRole>
    {
        public AppUserInRoleConfiguration()
            : this("dbo")
        {
        }

        public AppUserInRoleConfiguration(string schema)
        {
            Property(x => x.ValidTo).IsOptional();

            InitializePartial();
        }
        partial void InitializePartial();
    }

因此,我需要從此表方法中選擇數據:

public async Task<List<AppUserInRole>> GetUserRoles(long userId, bool onlyValid)
        {
            var data = from d in DataContext.AppUserInRoles
                where d.IdAppUser == userId
                select d;

            if (onlyValid)
                data = data.Between(DateTime.Now, a => a.ValidFrom, a => a.ValidTo ?? DateTime.MaxValue);

            return await data.ToListAsync();
        }

當我調用此方法時,實體框架將生成以下查詢:

SELECT 
    1 AS [C1], 
    [Extent1].[Id] AS [Id], 
    [Extent1].[IdAppUser] AS [IdAppUser], 
    [Extent1].[IdAppUserRole] AS [IdAppUserRole], 
    [Extent1].[ValidFrom] AS [ValidFrom], 
    [Extent1].[ValidTo] AS [ValidTo], 
    [Extent1].[CreatedDate] AS [CreatedDate], 
    [Extent1].[CreatedBy] AS [CreatedBy], 
    [Extent1].[AppUser_Id] AS [AppUser_Id], 
    [Extent1].[AppUser_Id1] AS [AppUser_Id1]
    FROM [dbo].[AppUserInRole] AS [Extent1]
    WHERE ([Extent1].[IdAppUser] = @p__linq__0) AND ([Extent1].[ValidFrom] <= convert(datetime2, '2017-07-31 22:13:26.6862657', 121)) AND (convert(datetime2, '2017-07-31 22:13:26.6862657', 121) <= (CASE WHEN ([Extent1].[ValidTo] IS NULL) THEN @p__linq__1 ELSE [Extent1].[ValidTo] END))

實體框架引發以下錯誤:無效的列名'AppUser_Id'。 無效的列名“ AppUser_Id1”。 AppUser_Id和AppUser_Id1列並沒有真正消失。 出於什么原因生成這些列?

非常感謝您的建議和幫助。

無法使用EF 6.1.3進行復制

create database foo
go
use foo
go
create table AppUser
(
 Id bigint primary key
)

create table AppUserRole
(
 Id bigint primary key
)

CREATE TABLE AppUserInRole
(
    Id              BIGINT          NOT NULL    IDENTITY PRIMARY KEY,                       
    IdAppUser       BIGINT          NOT NULL    FOREIGN KEY REFERENCES AppUser (Id),        
    IdAppUserRole   BIGINT          NOT NULL    FOREIGN KEY REFERENCES AppUserRole (Id),
    ValidFrom       DATETIME2       NOT NULL    DEFAULT GETDATE(),                          
    ValidTo         DATETIME2       NULL,                                                   
    CreatedDate     DATETIME2       NOT NULL    DEFAULT GETDATE(),                          
    CreatedBy       BIGINT  NULL FOREIGN KEY REFERENCES AppUser (Id),                                               
)

和:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace ConsoleApp6
{

    public class AppUser
    {
        public long Id { get; set; } // Id (Primary key)
    }

    public class AppUserRole
    {
        public long Id { get; set; } // Id (Primary key)
    }

    [Table("AppUserInRole", Schema = "dbo")]
    [System.CodeDom.Compiler.GeneratedCode("EF.Reverse.POCO.Generator", "2.31.1.0")]
    public partial class AppUserInRole
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [Column(@"Id", Order = 1, TypeName = "bigint")]
        [Required]
        [Key]
        [Display(Name = "Id")]
        public long Id { get; set; } // Id (Primary key)

        [Column(@"IdAppUser", Order = 2, TypeName = "bigint")]
        [Required]
        [Display(Name = "Id app user")]
        public long IdAppUser { get; set; } // IdAppUser

        [Column(@"IdAppUserRole", Order = 3, TypeName = "bigint")]
        [Required]
        [Display(Name = "Id app user role")]
        public long IdAppUserRole { get; set; } // IdAppUserRole

        [Column(@"ValidFrom", Order = 4, TypeName = "datetime2")]
        [Required]
        [Display(Name = "Valid from")]
        public System.DateTime ValidFrom { get; set; } = System.DateTime.Now; // ValidFrom

        [Column(@"ValidTo", Order = 5, TypeName = "datetime2")]
        [Display(Name = "Valid to")]
        public System.DateTime? ValidTo { get; set; } // ValidTo

        [Column(@"CreatedDate", Order = 6, TypeName = "datetime2")]
        [Required]
        [Display(Name = "Created date")]
        public System.DateTime CreatedDate { get; set; } = System.DateTime.Now; // CreatedDate

        [Column(@"CreatedBy", Order = 7, TypeName = "bigint")]
        [Required]
        [Display(Name = "Created by")]
        public long CreatedBy { get; set; } // CreatedBy

        // Foreign keys

        /// <summary>
        /// Parent AppUser pointed by [AppUserInRole].([CreatedBy]) (FK__AppUserIn__Creat__1AD3FDA4)
        /// </summary>
        [ForeignKey("CreatedBy")] public virtual AppUser AppUser_CreatedBy { get; set; } // FK__AppUserIn__Creat__1AD3FDA4
                                                                                         /// <summary>
                                                                                         /// Parent AppUser pointed by [AppUserInRole].([IdAppUser]) (FK__AppUserIn__IdApp__30F848ED)
                                                                                         /// </summary>
        [ForeignKey("IdAppUser")] public virtual AppUser AppUser_IdAppUser { get; set; } // FK__AppUserIn__IdApp__30F848ED
                                                                                         /// <summary>
                                                                                         /// Parent AppUserRole pointed by [AppUserInRole].([IdAppUserRole]) (FK__AppUserIn__IdApp__31EC6D26)
                                                                                         /// </summary>
        [ForeignKey("IdAppUserRole")] public virtual AppUserRole AppUserRole { get; set; } // FK__AppUserIn__IdApp__31EC6D26
    }

    [System.CodeDom.Compiler.GeneratedCode("EF.Reverse.POCO.Generator", "2.31.1.0")]
    public partial class AppUserInRoleConfiguration : System.Data.Entity.ModelConfiguration.EntityTypeConfiguration<AppUserInRole>
    {
        public AppUserInRoleConfiguration()
            : this("dbo")
        {
        }

        public AppUserInRoleConfiguration(string schema)
        {
            Property(x => x.ValidTo).IsOptional();

            InitializePartial();
        }
        partial void InitializePartial();
    }
    class Db: DbContext
    {
        public Db(string nameOrConnectionString) : base(nameOrConnectionString)
        {
        }

        public DbSet<AppUserInRole> AppUserInRoles { get; set; }

        public async Task<List<AppUserInRole>> GetUserRoles(long userId, bool onlyValid)
        {
            var data = from d in this.AppUserInRoles
                       where d.IdAppUser == userId
                       select d;

            if (onlyValid)
                data = data.Where(r => r.ValidFrom < DateTime.Now && (DateTime.Now < (r.ValidTo ?? DateTime.MaxValue)));

            return  await data.ToListAsync();
        }

    }
    class Program
    {

        static void Main(string[] args)
        {




            using (var db = new Db("Server=.;Database=foo;Integrated Security=true"))
            {
                db.Database.Log = m => Console.WriteLine(m);


                var data = db.GetUserRoles(1, true).Result;

            }

            Console.ReadKey();

        }
    }
}

產出

SELECT
    [Extent1].[Id] AS [Id],
    [Extent1].[IdAppUser] AS [IdAppUser],
    [Extent1].[IdAppUserRole] AS [IdAppUserRole],
    [Extent1].[ValidFrom] AS [ValidFrom],
    [Extent1].[ValidTo] AS [ValidTo],
    [Extent1].[CreatedDate] AS [CreatedDate],
    [Extent1].[CreatedBy] AS [CreatedBy]
    FROM [dbo].[AppUserInRole] AS [Extent1]
    WHERE ([Extent1].[IdAppUser] = @p__linq__0) AND ([Extent1].[ValidFrom] < (SysDateTime())) AND ((SysDateTime()) < (CASE WHEN ([Extent1].[ValidTo] IS NULL) THEN @p__linq__1 ELSE [Extent1].[ValidTo] END))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM