当我使用一个需要超过30秒才能完成的函数导入时,我使用实体框架(EF)得到超时。我尝试了以下方法,但未能解决此问题:

我将默认命令超时=300000添加到项目中的App.Config文件中的连接字符串中,该文件具有此处建议的EDMX文件。

这是我的连接字符串的样子:

<add 
    name="MyEntityConnectionString" 
    connectionString="metadata=res://*/MyEntities.csdl|res://*/MyEntities.ssdl|
       res://*/MyEntities.msl;
       provider=System.Data.SqlClient;provider connection string=&quot;
       Data Source=trekdevbox;Initial Catalog=StarTrekDatabase;
       Persist Security Info=True;User ID=JamesTKirk;Password=IsFriendsWithSpock;
       MultipleActiveResultSets=True;Default Command Timeout=300000;&quot;"
    providerName="System.Data.EntityClient" />

我尝试在我的存储库中直接设置CommandTimeout,如下所示:

private TrekEntities context = new TrekEntities();

public IEnumerable<TrekMatches> GetKirksFriends()
{
    this.context.CommandTimeout = 180;
    return this.context.GetKirksFriends();
}

我还能做什么来从计时超时中获得EF ?这只发生在非常大的数据集上。对于小型数据集,一切都很好。

这是我得到的错误之一:

entitycommandexecutionexception:在执行命令定义时发生错误。详情请参阅内部异常。——> System.Data.SqlClient.SqlException:超时。操作完成之前的超时时间或服务器没有响应。


好吧,我把它弄好了,发生的事情很愚蠢。我将连接字符串的Default CommandTimeout =300000和CommandTimeout设置为180。当我从连接字符串中删除默认命令超时时,它起作用了。所以答案是在你的存储库中手动设置CommandTimeout在你的context对象上,如下所示:

this.context.CommandTimeout = 180;

显然,在连接字符串中设置超时设置对它没有影响。

我已经为这个问题纠结了一段时间,不太明白发生了什么。我有一个卡片实体,它包含边(通常是2)-卡片和边都有一个阶段。我使用EF Codefirst迁移和迁移失败与此错误:

引入外键约束'FK_dbo.Sides_dbo。Cards_CardId” 表'Sides'可能会导致循环或多个级联路径。指定 DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他外键 约束。

这是我的Card实体:

public class Card
{
    public Card()
    {
        Sides = new Collection<Side>();
        Stage = Stage.ONE;
    }

    [Key]
    [Required]
    public virtual int CardId { get; set; }

    [Required]
    public virtual Stage Stage { get; set; }

    [Required]
    [ForeignKey("CardId")]
    public virtual ICollection<Side> Sides { get; set; }
}

这是我的Side实体:

public class Side
{
    public Side()
    {
        Stage = Stage.ONE;
    }

    [Key]
    [Required]     
    public virtual int SideId { get; set; } 

    [Required]
    public virtual Stage Stage { get; set; }

    [Required]
    public int CardId { get; set; }

    [ForeignKey("CardId")]
    public virtual Card Card { get; set; }

}

这是我的舞台实体:

public class Stage
{
    // Zero
    public static readonly Stage ONE = new Stage(new TimeSpan(0, 0, 0), "ONE");
    // Ten seconds
    public static readonly Stage TWO = new Stage(new TimeSpan(0, 0, 10), "TWO");

    public static IEnumerable<Stage> Values
    {
        get
        {
            yield return ONE;
            yield return TWO;
        }

    }

    public int StageId { get; set; }
    private readonly TimeSpan span;
    public string Title { get; set; }

    Stage(TimeSpan span, string title)
    {
        this.span = span;
        this.Title = title;
    }

    public TimeSpan Span { get { return span; } }
}

奇怪的是,如果我添加以下到我的Stage类:

    public int? SideId { get; set; }
    [ForeignKey("SideId")]
    public virtual Side Side { get; set; }

迁移成功。如果我打开SSMS并查看表格,我可以看到Stage_StageId已添加到Cards(正如预期/期望的那样),但是Sides没有包含对Stage的引用(不预期)。

如果我再加上

    [Required]
    [ForeignKey("StageId")]
    public virtual Stage Stage { get; set; }
    public int StageId { get; set; }

在Side类中,我看到StageId列添加到Side表中。

这是有效的,但是现在在整个应用程序中,任何对Stage的引用都包含一个SideId,这在某些情况下是完全不相关的。我想给我的卡和边实体一个基于上面的Stage类的Stage属性,如果可能的话,不要用引用属性污染Stage类……我做错了什么?

这看起来是一个非常普通的任务,但我找不到一个简单的方法来做。

我想撤消上一次应用的迁移。我本以为会有个简单的命令,比如

PM> Update-Database -TargetMigration:"-1"

相反,我能想到的只有:

PM> Get-Migrations

Retrieving migrations that have been applied to the target database.
201208012131302_Add-SystemCategory
201207311827468_CategoryIdIsLong
201207232247409_AutomaticMigration
201207211340509_AutomaticMigration
201207200025294_InitialCreate

PM> Update-Database -TargetMigration:"CategoryIdIsLong"

(至少我可以只使用名称,跳过时间戳…)

有没有更简单的方法?

我有这个查询,我得到了这个函数的错误:

var accounts = from account in context.Accounts
               from guranteer in account.Gurantors
               select new AccountsReport
               {
                   CreditRegistryId = account.CreditRegistryId,
                   AccountNumber = account.AccountNo,
                   DateOpened = account.DateOpened,
               };

 return accounts.AsEnumerable()
                .Select((account, index) => new AccountsReport()
                    {
                        RecordNumber = FormattedRowNumber(account, index + 1),
                        CreditRegistryId = account.CreditRegistryId,
                        DateLastUpdated = DateLastUpdated(account.CreditRegistryId, account.AccountNumber),
                        AccountNumber = FormattedAccountNumber(account.AccountType, account.AccountNumber)
                    })
                .OrderBy(c=>c.FormattedRecordNumber)
                .ThenByDescending(c => c.StateChangeDate);


public DateTime DateLastUpdated(long creditorRegistryId, string accountNo)
{
    return (from h in context.AccountHistory
            where h.CreditorRegistryId == creditorRegistryId && h.AccountNo == accountNo
            select h.LastUpdated).Max();
}

错误:

已经有一个打开的DataReader与此命令相关联,必须先关闭它。

更新:

添加堆栈跟踪:

InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.]
   System.Data.SqlClient.SqlInternalConnectionTds.ValidateConnectionForExecute(SqlCommand command) +5008639
   System.Data.SqlClient.SqlConnection.ValidateConnectionForExecute(String method, SqlCommand command) +23
   System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async) +144
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +87
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +32
   System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +141
   System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +12
   System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +10
   System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) +443

[EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details.]
   System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) +479
   System.Data.Objects.Internal.ObjectQueryExecutionPlan.Execute(ObjectContext context, ObjectParameterCollection parameterValues) +683
   System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) +119
   System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator() +38
   System.Linq.Enumerable.Single(IEnumerable`1 source) +114
   System.Data.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__3(IEnumerable`1 sequence) +4
   System.Data.Objects.ELinq.ObjectQueryProvider.ExecuteSingle(IEnumerable`1 query, Expression queryRoot) +29
   System.Data.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute(Expression expression) +91
   System.Data.Entity.Internal.Linq.DbQueryProvider.Execute(Expression expression) +69
   System.Linq.Queryable.Max(IQueryable`1 source) +216
   CreditRegistry.Repositories.CreditRegistryRepository.DateLastUpdated(Int64 creditorRegistryId, String accountNo) in D:\Freelance Work\SuperExpert\CreditRegistry\CreditRegistry\Repositories\CreditRegistryRepository.cs:1497
   CreditRegistry.Repositories.CreditRegistryRepository.<AccountDetails>b__88(AccountsReport account, Int32 index) in D:\Freelance Work\SuperExpert\CreditRegistry\CreditRegistry\Repositories\CreditRegistryRepository.cs:1250
   System.Linq.<SelectIterator>d__7`2.MoveNext() +198
   System.Linq.Buffer`1..ctor(IEnumerable`1 source) +217
   System.Linq.<GetEnumerator>d__0.MoveNext() +96

我在用代码优先方法播种数据库时遇到了这个错误。

一个或多个实体的验证失败。有关详细信息,请参阅“EntityValidationErrors”属性。

老实说,我不知道如何检查验证错误的内容。Visual Studio向我展示了它是一个包含8个对象的数组,因此有8个验证错误。

这适用于我以前的模型,但我做了一些更改,我将在下面解释:

我有一个名为Status的枚举,我将其更改为名为Status我将类ApplientsPositionHistory更改为具有同一表的2个外键

对不起,代码太长了,但我必须全部粘贴。异常在以下代码的最后一行中引发。

namespace Data.Model
{  
    public class Position
    {
        [DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.Identity)]   
        public int PositionID { get; set; }

        [Required(ErrorMessage = "Position name is required.")]
        [StringLength(20, MinimumLength = 3, ErrorMessage = "Name should not be longer than 20 characters.")]
        [Display(Name = "Position name")]              
        public string name { get; set; }

        [Required(ErrorMessage = "Number of years is required")] 
        [Display(Name = "Number of years")]        
        public int yearsExperienceRequired { get; set; }

        public virtual ICollection<ApplicantPosition> applicantPosition { get; set; }
    }

    public class Applicant
    {
        [DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.Identity)]      
        public int ApplicantID { get; set; }

        [Required(ErrorMessage = "Name is required")] 
        [StringLength(20, MinimumLength = 3, ErrorMessage="Name should not be longer than 20 characters.")]
        [Display(Name = "First and LastName")]
        public string name { get; set; }

        [Required(ErrorMessage = "Telephone number is required")] 
        [StringLength(10, MinimumLength = 3, ErrorMessage = "Telephone should not be longer than 20 characters.")]
        [Display(Name = "Telephone Number")]
        public string telephone { get; set; }

        [Required(ErrorMessage = "Skype username is required")] 
        [StringLength(10, MinimumLength = 3, ErrorMessage = "Skype user should not be longer than 20 characters.")]
        [Display(Name = "Skype Username")]
        public string skypeuser { get; set; }

        public byte[] photo { get; set; }

        public virtual ICollection<ApplicantPosition> applicantPosition { get; set; }
    }

    public class ApplicantPosition
    {
        [Key]
        [Column("ApplicantID", Order = 0)]
        public int ApplicantID { get; set; }

        [Key]
        [Column("PositionID", Order = 1)]
        public int PositionID { get; set; }

        public virtual Position Position { get; set; }

        public virtual Applicant Applicant { get; set; }

        [Required(ErrorMessage = "Applied date is required")] 
        [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
        [Display(Name = "Date applied")]     
        public DateTime appliedDate { get; set; }

        [Column("StatusID", Order = 0)]
        public int StatusID { get; set; }

        public Status CurrentStatus { get; set; }

        //[NotMapped]
        //public int numberOfApplicantsApplied
        //{
        //    get
        //    {
        //        int query =
        //             (from ap in Position
        //              where ap.Status == (int)Status.Applied
        //              select ap
        //                  ).Count();
        //        return query;
        //    }
        //}
    }

    public class Address
    {
        [StringLength(20, MinimumLength = 3, ErrorMessage = "Country should not be longer than 20 characters.")]
        public string Country { get; set; }

        [StringLength(20, MinimumLength = 3, ErrorMessage = "City  should not be longer than 20 characters.")]
        public string City { get; set; }

        [StringLength(50, MinimumLength = 3, ErrorMessage = "Address  should not be longer than 50 characters.")]
        [Display(Name = "Address Line 1")]     
        public string AddressLine1 { get; set; }

        [Display(Name = "Address Line 2")]
        public string AddressLine2 { get; set; }   
    }

    public class ApplicationPositionHistory
    {
        [DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.Identity)]
        public int ApplicationPositionHistoryID { get; set; }

        public ApplicantPosition applicantPosition { get; set; }

        [Column("oldStatusID")]
        public int oldStatusID { get; set; }

        [Column("newStatusID")]
        public int newStatusID { get; set; }

        public Status oldStatus { get; set; }

        public Status newStatus { get; set; }

        [StringLength(500, MinimumLength = 3, ErrorMessage = "Comments  should not be longer than 500 characters.")]
        [Display(Name = "Comments")]
        public string comments { get; set; }

        [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
        [Display(Name = "Date")]     
        public DateTime dateModified { get; set; }
    }

    public class Status
    {
        [DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.Identity)]
        public int StatusID { get; set; }

        [StringLength(20, MinimumLength = 3, ErrorMessage = "Status  should not be longer than 20 characters.")]
        [Display(Name = "Status")]
        public string status { get; set; }
    }
}

使用系统;使用System.Collections.Generic;使用System.Linq;使用System.Text;使用System.Data.Entity;使用System.IO;命名空间Data.Model{公共类HRContextInitializer:DropCreateDatabaseAlways<HRContext>{受保护的覆盖void Seed(HRContext上下文){#地区状态已应用状态=新状态(){Status=“已应用”};状态reviewedByHR=新状态(){Status=“人力资源审核”};状态approvedByHR=新状态(){Status=“已由HR批准”};Status rejectedByHR=新状态(){Status=“被HR拒绝”};分配给技术部门的状态=新状态(){Status=“分配给技术部”};技术部门批准的状态=新状态(){Status=“技术部门批准”};技术部门拒绝的状态=新状态(){Status=“技术部门拒绝”};Status assignedToGeneral Manager=新状态(){Status=“分配给General Manager”};状态approvedByGeneralManager=新状态(){Status=“已由总经理批准”};Status rejectedByGeneralManager=新状态(){Status=“被总经理拒绝”};context.Status.Add(已应用);context.Status.Add(由HR审查);context.Status.Add(已由HR批准);context.Status.Add(被HR拒绝);context.Status.Add(分配给技术部门);context.Status.Add(由技术部门批准);context.Status.Add(被技术部门拒绝);context.Status.Add(分配给GeneralManager);context.Status.Add(由GeneralManager批准);context.Status.Add(被GeneralManager拒绝);#末端区域#区域位置职位netdeveloper=new职位(){name=“.net developer”,所需年经验=5};职位javadeveloper=new Position(){name=“java developer”,yearsExperienceRequired=5};context.Positions.Add(netdeveloper);context.Positions.Add(javadeveloper);#末端区域#地区申请人申请人luis=新申请人(){name=“Luis”,skypeuser=“le.valencia”,电话=“0491732825”,photo=文件.ReadAllBytes(@“C:\Users\LUIS.SIMBIOS\Documents\Visual Studio 2010\Projects\SlnHR\HRRazorForms\Content\pictures\1.jpg”)};申请人john=新申请人(){name=“John”,skypeuser=“jo.valencia”,电话=“3435343543”,photo=文件.ReadAllBytes(@“C:\Users\LUIS.SIMBIOS\Documents\Visual Studio 2010\Projects\SlnHR\HRRazorForms\Content\pictures\2.jpg”)};context.申请人.添加(luis);context.申请人.Add(john);#末端区域#区域应用程序位置ApplicantPosition appicantposition=新的ApplicantPosition(){申请人=luis,位置=网络开发者,appliedDate=日期时间。今天,状态ID=1};ApplicantPosition appicantposition2=新的ApplicantPosition(){申请人=john,位置=javadeveloper,appliedDate=日期时间。今天,状态ID=1}; context.ApplicantsPosition.Add(applicantposition);context.ApplicantsPositions.Add(applicantposition2);#末端区域context.SaveChanges();--->>此处出错}}}