Subsonic 3 Active Record TestRepository identity column not incremented

混江龙づ霸主 提交于 2019-12-10 12:14:47

问题


I am Unit Testing with Subsonic 3.0.0.3. Unit tests ran as expected with record count assertions passing. However the testing framework does not auto increment identity columns.

For example

var p1 = new Person() { Name = "Jack" };
p1.Add();
var p2 = new Person() { Name = "Jill" };
p2..Add();
var t1 = Person.SingleOrDefault(p => p.Name == "Jack");
var t2 = Person.SingleOrDefault(p => p.Name == "Jill");

Table structure read by the T4 template

CREATE TABLE Person
(
    Id int IDENTITY(1,1) PRIMARY KEY
    ,Name NVARCHAR(255) NOT NULL 
)

Connection string

<add name="SomeDb" connectionString="Test"/>

t1 and t2 have the name property set as expected, but the Id property is 0 for both.

Is this by design? If so how to deal with tests that require selecting records by ID?


回答1:


The TestRepository has no idea how your DB bits are set (how could it?) so if you want it to auto-increment you'll need to set it yourself.




回答2:


Here's a change to the ActiveRecord template that I find useful. Basically it handles an int or long primary key column and in test mode auto allocates a new id. Requires two changes to the ActiveRecord.tt template:

1: In the top of the function public void Add(IDataProvider provider){

        public void Add(IDataProvider provider){

<#if(tbl.PK.SysType=="long" || tbl.PK.SysType=="int") {#>
            if (TestMode)
            {
                this.<#=tbl.PK.CleanName#>=++next_test_autoid;
            }

<#}#>

2: Under the line public bool TestMode = false, add:

        public bool TestMode = false;
<#if(tbl.PK.SysType=="long" || tbl.PK.SysType=="int") {#>
        private static <#=tbl.PK.SysType#> next_test_autoid = 0;
<#}#>



回答3:


(I don't have enough points to comment yet, but this is in response to cantabilesoftware's answer.)

I have a subtype relationship in my database where two tables are 1->1. I had to modify your template slightly to skip the logic if the key field already has a value assigned:

<#if(tbl.PK.SysType=="long" || tbl.PK.SysType=="int") {#>
            if (TestMode && <#=tbl.PK.CleanName#> == 0)
            {
                this.<#=tbl.PK.CleanName#>=++next_test_autoid;
            }
<#}#>


来源:https://stackoverflow.com/questions/1508706/subsonic-3-active-record-testrepository-identity-column-not-incremented

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!