Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FreeSql.Provider.SqlServer SeedData List集合时无法正常增加分表的种子数据 #362

Closed
luoyunchong opened this issue Jul 5, 2020 · 5 comments

Comments

@luoyunchong
Copy link
Collaborator

数据库:Sql server 2017
驱动: FreeSql.Provider.SqlServer Version="1.6.0"

我写了个demo作为参考sqlserver-seeddata-problem.zip

image

此demo,他只会增加主表的Blog的二条数据。Posts(评论回复)无法增加


            Fsql.CodeFirst.Entity<Blog>(e =>
            {

                e.HasData(new List<Blog>()
                {
                        new Blog("title","content",DateTime.Now,false)
                        {
                            Posts=new List<Post>
                            {
                                new Post("replyContent",DateTime.Now,false),
                                new Post("replyContent",DateTime.Now,false),
                                new Post("replyContent",DateTime.Now,false),
                            }
                        },
                        new Blog("title","content",DateTime.Now,false)
                        {
                            Posts=new List<Post>
                            {
                                new Post("replyContent",DateTime.Now,false),
                                new Post("replyContent",DateTime.Now,false),
                                new Post("replyContent",DateTime.Now,false),
                            }
                        }
                });
            });

但如果只有一条Blog的数据时,分表的数据能正常增加


            Fsql.CodeFirst.Entity<Blog>(e =>
            {

                e.HasData(new List<Blog>()
                {
                        new Blog("title","content",DateTime.Now,false)
                        {
                            Posts=new List<Post>
                            {
                                new Post("replyContent",DateTime.Now,false),
                                new Post("replyContent",DateTime.Now,false),
                                new Post("replyContent",DateTime.Now,false),
                            }
                        }
                });
            });

SeedData 种子数据,我试了下在MySql和Sqlite下都能正常生成种子数据,然后到了SqlServer下,就会出现如下错误

     NullReferenceException: Object reference not set to an instance of an object.
lambda_method(Closure , object , object )
FreeSql.Extensions.EntityUtil.EntityUtilExtensions.MapEntityValue(IFreeSql orm, Type entityType, object entityFrom, object entityTo)
FreeSql.DbSet<TEntity>.AddRange(IEnumerable<TEntity> data)
FreeSql.BaseRepository<TEntity>.Insert(IEnumerable<TEntity> entitys)
FreeSql.Extensions.EfCoreFluentApi.EfCoreTableFluent<T>+<>c__DisplayClass17_0.<HasData>b__1(object s, SyncStructureAfterEventArgs e)
FreeSql.Internal.CommonProvider.CodeFirstProvider.SyncStructure(TypeAndName[] objects)
FreeSql.Internal.CommonProvider.CodeFirstProvider.SyncStructure<TEntity>()
FreeSql.Internal.CommonProvider.Select0Provider<TSelect, T1>..ctor(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere)
FreeSql.Internal.CommonProvider.Select1Provider<T1>..ctor(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere)
FreeSql.SqlServer.Curd.SqlServerSelect<T1>..ctor(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere)
FreeSql.SqlServer.SqlServerProvider<TMark>.Select<T1>()
sqlserver_seeddata_problem.Controllers.BlogController.GetBlogs() in BlogController.cs
-
        {
            this.freeSql = freeSql;
        }
        public List<Blog> GetBlogs()
        {
            return freeSql.Select<Blog>().ToList();
        }
    }
}
lambda_method(Closure , object , object[] )
Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(object target, object[] parameters)
Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor+SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, object controller, object[] arguments)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Logged|12_1(ControllerActionInvoker invoker)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
@2881099
Copy link
Collaborator

2881099 commented Jul 5, 2020

问题确实存在,是 AsType 操作之后用 ExecuteInserted() 执行导致返回了字典,我处理一下

@2881099
Copy link
Collaborator

2881099 commented Jul 5, 2020

解决了 1.7.0-preview0705

@luoyunchong
Copy link
Collaborator Author

👍好的。已安装使用没问题。

@luoyunchong
Copy link
Collaborator Author

另一个sqlserver的问题。
测试工程中的AsSelect增加如下代码

      var t3 = g.sqlserver.Select<Song>()
               .ToList(r => new
               {
                   r.Title,
                   count = r.Tags.AsSelect().Count()
               });

image

 FreeSql.Tests.SqlServer.SqlServerSelectTest.AsSelect
   源: SqlServerSelectTest.cs 行 83
   持续时间: 3.8 秒

  消息: 
    System.Exception : 关键字 'exists' 附近有语法错误。
    “as2”附近有语法错误。
    ---- System.Data.SqlClient.SqlException : 关键字 'exists' 附近有语法错误。
    “as2”附近有语法错误。
  堆栈跟踪: 
    Select0Provider`2.ToListMrPrivate[TReturn](String sql, ReadAnonymousTypeAfInfo af, ReadAnonymousTypeOtherInfo[] otherData) 行 555
    Select0Provider`2.ToListMapReaderPrivate[TReturn](ReadAnonymousTypeAfInfo af, ReadAnonymousTypeOtherInfo[] otherData) 行 580
    Select0Provider`2.ToListMapReader[TReturn](ReadAnonymousTypeAfInfo af) 行 582
    Select0Provider`2.InternalToList[TReturn](Expression select) 行 1272
    Select1Provider`1.ToList[TReturn](Expression`1 select) 行 175
    SqlServerSelectTest.AsSelect() 行 116
    ----- Inner Stack Trace -----
    SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
    SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
    TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
    TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
    SqlDataReader.TryConsumeMetaData()
    SqlDataReader.get_MetaData()
    SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
    SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
    SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite, String method)
    SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
    SqlCommand.ExecuteReader(CommandBehavior behavior)
    SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
    DbCommand.ExecuteReader()
    AdoProvider.ExecuteReaderMultiple(Int32 multipleResult, DbConnection connection, DbTransaction transaction, Action`2 readerHander, CommandType cmdType, String cmdText, DbParameter[] cmdParms) 行 603

生成的sql

SELECT a.[Title] as1, exists(SELECT TOP 1 1 
	FROM [Song_tag] Mtb_2_Mr 
	WHERE (Mtb_2_Mr.[Song_id] = a.[Id]) AND (exists(SELECT TOP 1 1 
		FROM [Tag] tb_2 
			WHERE (tb_2.[Id] = Mtb_2_Mr.[Tag_id])))) as2 
FROM [Song] a

@2881099
Copy link
Collaborator

2881099 commented Jul 6, 2020

多对多 select 查询不好处理,因为是一对多的关系,1.6.0 和之前的版本 使用 exists 方式处理的,所以报了这个错误。

暂时可以把 AsSelect().Count() 也兼容一下,AsSelect(). Sum/Avg/Max/Min/First/ToOne/ToList 暂时处理不了。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants