Quantcast
Channel: EntityFramework Reverse POCO Code First Generator
Viewing all 1642 articles
Browse latest View live

Created Unassigned: using DB "newsequentialid()" to help with indexing [174]

$
0
0
We have a database that now has a surrogate key that we use for lookup. We have it set as a "UniqueIdentifier" and have a default value of "newsequentialid()". We want to use the sqeuential id from MSSQL as when when index on the value it will make for better paging. I have changed the code in the core ttinclude to set the column as "IsStoreGenerated" = 1. Here is the code that i have created.

```
CAST(CASE WHEN COLUMNPROPERTY(OBJECT_ID(QUOTENAME(c.TABLE_SCHEMA) + '.' + QUOTENAME(c.TABLE_NAME)), c.COLUMN_NAME, 'IsIdentity') = 1 THEN 1
WHEN COLUMNPROPERTY(OBJECT_ID(QUOTENAME(c.TABLE_SCHEMA) + '.' + QUOTENAME(c.TABLE_NAME)), c.COLUMN_NAME, 'IsComputed') = 1 THEN 1
WHEN DATA_TYPE = 'TIMESTAMP' THEN 1
WHEN DATA_TYPE = 'UNIQUEIDENTIFIER' AND ISNULL(COLUMN_DEFAULT, '') = '(newsequentialid())' THEN 1
ELSE 0
END AS BIT) AS IsStoreGenerated,
```
I did not change the constructor of the class as since the column will now be set to "HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed)" and EF will ignore the value anyway

Commented Unassigned: ReadStoredProcReturnObject throws an exception if a parameter contains a user defined type [173]

$
0
0
Hi,

The generated query used to work out the return model of a stored proc in invalid if it contains a user defined type.

The tool generates the following query for a stored proc in my database:

```
SET FMTONLY OFF; SET FMTONLY ON;
EXEC [Products].[ShipGoodsOut] @carrier=null, @service=null, @trackingNumber=null, @goodsOutIds=null
SET FMTONLY OFF; SET FMTONLY OFF;
```

The last parameter is a user defined table type:

```
CREATE TYPE [dbo].[Ids] AS TABLE(
[Id] [int] NOT NULL
)
```

Running the generated query gives the following error:

> Msg 206, Level 16, State 2, Procedure ShipGoodsOut, Line 13
Operand type clash: NULL is incompatible with Ids


That causes an exception and means the code required to populate the return model is never generated and so it fallsback to the code required to set the out parameter.

If I change the query such that it looks like this:

```
SET FMTONLY OFF; SET FMTONLY ON;
DECLARE @carrier varchar(25)
DECLARE @service varchar(25)
DECLARE @trackingNumber varchar(25)
DECLARE @goodsOutIds [dbo].[Ids]
EXEC [Products].[ShipGoodsOut] @carrier, @service, @trackingNumber, @goodsOutIds
SET FMTONLY OFF; SET FMTONLY OFF;
```

It works fine.
Comments: Actually, there is a small issue with the code above. It should be: ``` var sb = new StringBuilder(); sb.Append("SET FMTONLY OFF; SET FMTONLY ON; \n"); if (proc.IsTVF) { sb.Append(String.Format("SELECT * FROM [{0}].[{1}](", proc.Schema, proc.Name)); foreach (var param in proc.Parameters) { sb.Append("null, "); } if (proc.Parameters.Count > 0) sb.Length -= 2; sb.Append(")"); } else { foreach (var param in proc.Parameters) { sb.AppendLine(String.Format("DECLARE {0} {1}", param.Name, param.SqlDbType == "Structured" ? param.UserDefinedTypeName : param.SqlDbType)); } sb.Append(String.Format("exec [{0}].[{1}] ", proc.Schema, proc.Name)); foreach (var param in proc.Parameters) { sb.Append(String.Format("{0}, ", param.Name)); } if (proc.Parameters.Count > 0) sb.Length -= 2; } sb.Append("\n SET FMTONLY OFF; SET FMTONLY OFF;"); ```

New Post: Navigation properties collection type

New Post: donation + some feature requests

$
0
0
Hey Simon,

great, thank you very much. I havn't tried it yet but I will in the next weeks. I introduced your generator in my team. The more we use it, the more we like it. So thanks again for this. Some minor! requests came up, which I'll report next week. Have a nice weekend.

Mathias

Created Unassigned: Compilation error when generating stored proc return models in POCO assembly [175]

$
0
0
Hi,

Since v2.17.1 I have been able to generate stored proc return models in the POCO assembly. This assembly does not have a reference to EF. However, the new version, v2.17.2, has changed the usings in the generated POCO classes - it now includes "using System.Data.Entity.Infrastructure;" and "using System.Data.Entity.Core.Objects;". The assembly won't build because it does not reference EF. Please can you restore the previous behaviour.

Thanks,
Andy

New Post: Adding a metadata attribute?

$
0
0
Hi Simon,

Does your generator create a MetadataType attribute for data domain class?

For example:
[MetadataType(typeof(ContactMetadata))]
public class Contact
{
      public long CustomerId { get; set; } // Primary Key
      public string Name { get; set; }
      public string Address { get; set; }
      ... etc., etc...
}
If not, could it be added?

Steve

New Post: Adding a metadata attribute?

$
0
0
The generator is setup so you can add whatever attribute you need to your classes. See WritePocoClassAttributes.

For example:
AdditionalNamespaces = new[] { "System", "System.ComponentModel.DataAnnotations" };
Action<Table> WritePocoClassAttributes = t =>
{
    WriteLine("    [MetadataType(typeof(" + t.ClassName + "Metadata))]");
};
You would then have to add the <class>Metadata classes to your project separately.

Created Unassigned: adding Visual Studio Installer Setup Project to Solution causes issues [176]

$
0
0
Hi Simon,
When adding a Installer Setup Project to a VS2015 Windows Service project, the poco generator fails. I think it is looking for a config file within the installer project. I "attempted" to debug the .tt file but that just added to my confusion. Am I missing something simple?

Severity Code Description Project File Line
Error Running transformation: System.ArgumentNullException: Value cannot be null.
Parameter name: source
at System.Linq.Enumerable.Cast[TResult](IEnumerable source)
at Microsoft.VisualStudio.TextTemplating4F7B8D9CDB82346626B41E8D67DD2DF6E5570318C72F9EF6F35975B5ED5379B2557537AE3B4A7D1B71C9DC4CC21B5BB7C9C66D8B92591974F756BB3559A8FB62.GeneratedTextTransformation.GetConfigPathsInProjectForFile(Project project, String filename)
at Microsoft.VisualStudio.TextTemplating4F7B8D9CDB82346626B41E8D67DD2DF6E5570318C72F9EF6F35975B5ED5379B2557537AE3B4A7D1B71C9DC4CC21B5BB7C9C66D8B92591974F756BB3559A8FB62.GeneratedTextTransformation.GetConfigPathsInProject(Project project)
at Microsoft.VisualStudio.TextTemplating4F7B8D9CDB82346626B41E8D67DD2DF6E5570318C72F9EF6F35975B5ED5379B2557537AE3B4A7D1B71C9DC4CC21B5BB7C9C66D8B92591974F756BB3559A8FB62.GeneratedTextTransformation.GetConfigPaths()
at Microsoft.VisualStudio.TextTemplating4F7B8D9CDB82346626B41E8D67DD2DF6E5570318C72F9EF6F35975B5ED5379B2557537AE3B4A7D1B71C9DC4CC21B5BB7C9C66D8B92591974F756BB3559A8FB62.GeneratedTextTransformation.GetConnectionString(String& connectionStringName, String& providerName, String& configFilePath)
at Microsoft.VisualStudio.TextTemplating4F7B8D9CDB82346626B41E8D67DD2DF6E5570318C72F9EF6F35975B5ED5379B2557537AE3B4A7D1B71C9DC4CC21B5BB7C9C66D8B92591974F756BB3559A8FB62.GeneratedTextTransformation.InitConnectionString()
at Microsoft.VisualStudio.TextTemplating4F7B8D9CDB82346626B41E8D67DD2DF6E5570318C72F9EF6F35975B5ED5379B2557537AE3B4A7D1B71C9DC4CC21B5BB7C9C66D8B92591974F756BB3559A8FB62.GeneratedTextTransformation.GetDbProviderFactory()
at Microsoft.VisualStudio.TextTemplating4F7B8D9CDB82346626B41E8D67DD2DF6E5570318C72F9EF6F35975B5ED5379B2557537AE3B4A7D1B71C9DC4CC21B5BB7C9C66D8B92591974F756BB3559A8FB62.GeneratedTextTransformation.TransformText() rcrs_server_its C:\_VS2010\GIS_dt_RCRS_Server_ITS\DEV\Src\rcrs_server_its\rcrs_server_its\Data\dot_rcrs.tt 1


New Post: From this to WEB API OData for AdventureWorks

$
0
0
Hello all,

What would it take to go from the AdventureWorks (AW) database and expose a WEB API OData REST service for all of it? Is it pretty straight-forward or needs a lot of tinkering? I see AW has things like hierarchyId, a (base?) BusinessEntity table, different schemas, composite keys, relationships/foreignKeys etc. A lot of other examples I see are very simple. What are some of the gotcha's and tip & tricks, what to avoid, workarounds?

Has anyone exposed AW with latest WEB API OData (perhaps with this) or know where? Thanks.

I tried to do the above, but currently cannot get any data out, with error

{
"error": {
"code": "",
"message": "An error has occurred.",
"innererror": {
  "message": "The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; odata.metadata=minimal'.",
  "type": "System.InvalidOperationException",
  "stacktrace": "",
  "internalexception": {
    "message": "Sequence contains no matching element",
    "type": "System.InvalidOperationException",
    "stacktrace": "   at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source, Func`2 predicate)\r\n   at System.Data.Entity.Utilities.DbProviderManifestExtensions.GetStoreTypeFromName(DbProviderManifest providerManifest, String name)\r\n   at System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.ConfigureColumn(EdmProperty column, EntityType table, DbProviderManifest providerManifest)\r\n   at System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.Configure(EdmProperty column, EntityType table, DbProviderManifest providerManifest, Boolean allowOverride, Boolean fillFromExistingConfiguration)\r\n   at System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.<>c__DisplayClass4.<Configure>b__3(Tuple`2 pm)\r\n   at System.Data.Entity.Utilities.IEnumerableExtensions.Each[T](IEnumerable`1 ts, Action`1 action)\r\n   at System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.Configure(IEnumerable`1 propertyMappings, DbProviderManifest providerManifest, Boolean allowOverride, Boolean fillFromExistingConfiguration)\r\n   at System.Data.Entity.ModelConfiguration.Configuration.Types.StructuralTypeConfiguration.ConfigurePropertyMappings(IList`1 propertyMappings, DbProviderManifest providerManifest, Boolean allowOverride)\r\n   at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.ConfigurePropertyMappings(DbDatabaseMapping databaseMapping, EntityType entityType, DbProviderManifest providerManifest, Boolean allowOverride)\r\n   at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.Configure(EntityType entityType, DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)\r\n   at System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.ConfigureEntityTypes(DbDatabaseMapping databaseMapping, ICollection`1 entitySets, DbProviderManifest providerManifest)\r\n   at System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.Configure(DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)\r\n   at System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo)\r\n   at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)\r\n   at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)\r\n   at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)\r\n   at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()\r\n   at System.Data.Entity.Internal.InternalContext.Initialize()\r\n   at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)\r\n   at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()\r\n   at System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator()\r\n   at System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.IEnumerable.GetEnumerator()\r\n   at System.Web.OData.Formatter.Serialization.ODataFeedSerializer.WriteFeed(IEnumerable enumerable, IEdmTypeReference feedType, ODataWriter writer, ODataSerializerContext writeContext)\r\n   at System.Web.OData.Formatter.Serialization.ODataFeedSerializer.WriteObjectInline(Object graph, IEdmTypeReference expectedType, ODataWriter writer, ODataSerializerContext writeContext)\r\n   at System.Web.OData.Formatter.Serialization.ODataFeedSerializer.WriteObject(Object graph, Type type, ODataMessageWriter messageWriter, ODataSerializerContext writeContext)\r\n   at System.Web.OData.Formatter.ODataMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content, HttpContentHeaders contentHeaders)\r\n   at System.Web.OData.Formatter.ODataMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()\r\n   at System.Web.Http.WebHost.HttpControllerHandler.<WriteBufferedResponseContentAsync>d__1b.MoveNext()"
  }
}
}
}

New Post: add hasoptional relationship which doesn't exist in DB

$
0
0
Please allow me to join with the others in thanking you for the substantial and useful tool.

I have a DB which started with an early EF revision. It successfully transitioned to EF4, then 5. Now we are attempting to position it for the future. I've had an number of issue, but found answers for everything but this so far by trolling the discussion group.

I have two tables, primary table EntryLog, child table ContactedEntryLogDetail. The primary key on both tables is LogEntryId. The child table primary key is not an identity column.

There is no relationship in the db between these two tables. When there is a ContactedEntryLogDetail (which there is not always), the child key entry is supposed to be equal to the parent primary key.

in the old edmx file I see:
</AssociationSet>
      <EntitySet Name="ContactedLogEntryDetails" EntityType="AWCTSDBModel.ContactedLogEntryDetail" />
      <EntitySet Name="LogEntries" EntityType="AWCTSDBModel.LogEntry" />
      <AssociationSet Name="FK_ContactedLogEntryDetailsLogEntry" Association="AWCTSDBModel.FK_ContactedLogEntryDetailsLogEntry">
        <End Role="LogEntry" EntitySet="LogEntries" />
        <End Role="ContactedLogEntryDetail" EntitySet="ContactedLogEntryDetails" />
      </AssociationSet>

      <NavigationProperty Name="LogEntry" Relationship="AWCTSDBModel.FK_ContactedLogEntryDetailsLogEntry" FromRole="ContactedLogEntryDetail" ToRole="LogEntry" />

      <NavigationProperty Name="ContactedLogEntryDetail" Relationship="AWCTSDBModel.FK_ContactedLogEntryDetailsLogEntry" FromRole="LogEntry" ToRole="ContactedLogEntryDetail" />

    <Association Name="FK_ContactedLogEntryDetailsLogEntry">
      <End Type="AWCTSDBModel.LogEntry" Role="LogEntry" Multiplicity="1" />
      <End Type="AWCTSDBModel.ContactedLogEntryDetail" Role="ContactedLogEntryDetail" Multiplicity="0..1" />
      <ReferentialConstraint>
        <Principal Role="LogEntry">
          <PropertyRef Name="LogEntryId" />
        </Principal>
        <Dependent Role="ContactedLogEntryDetail">
          <PropertyRef Name="LogEntryId" />
        </Dependent>
      </ReferentialConstraint>
    </Association>
If I look at the edmx design, I see a 1:0-1 relationship between these tables. I don't see this relationship defined in the db and I can't add this relationship in the db to reverse.

Based on my reading it seems I need an hasOptional statement associated with one of these tables, but I can't figure out where I would put it.

If none of this makes sense, I can code around this problem. But if you see a solution, I would really appreciate it, as this situation occurs with a large number of tables.

Thank you,
jeff landry

New Post: table specifies primary key different from base table

$
0
0
The app has two classes: case and AWCase. AWCase descends from case. case.caseId is the primary key for both classes. I expect AWCase to inherit caseId from case.

When I run the program I get a message:
Conflicting configuration settings were specified for property 'CaseId' on type 'AWCTSModel.Case':
DatabaseGeneratedOption = None conflicts with DatabaseGeneratedOption = Identity]
When I look at the generated model file I find that both case and AWCase have caseId defined and the definitions conflict.

What am I doing wrong? Generated code shown below.

Thank you,
jeff

I designate inheritance in WritePocoBaseClasses:
    if (t.ClassName == "AWCase")
        return ": Case";

// Case
[GeneratedCodeAttribute("EF.Reverse.POCO.Generator", "2.17.2.0")]
public partial class Case
{

public long CaseId { get; set; } // CaseId (Primary key)

// Case
public partial class CaseConfiguration : EntityTypeConfiguration<Case>
{
    public CaseConfiguration()
        : this("dbo")
    {
    }

    public CaseConfiguration(string schema)
    {
        ToTable(schema + ".Case");
        HasKey(x => x.CaseId);

        Property(x => x.CaseId).HasColumnName("CaseId").IsRequired().HasColumnType("bigint").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
=====
// AWCase
[GeneratedCodeAttribute("EF.Reverse.POCO.Generator", "2.17.2.0")]
public partial class AWCase: Case
{

public long CaseId { get; set; } // CaseId (Primary key)

// AWCase
public partial class AWCaseConfiguration : EntityTypeConfiguration<AWCase>
{
    public AWCaseConfiguration()
        : this("dbo")
    {
    }

    public AWCaseConfiguration(string schema)
    {
        ToTable(schema + ".AWCase");
        HasKey(x => x.CaseId);

        Property(x => x.CaseId).HasColumnName("CaseId").IsRequired().HasColumnType("bigint").HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

Edited Issue: ReadStoredProcReturnObject throws an exception if a parameter contains a user defined type [173]

$
0
0
Hi,

The generated query used to work out the return model of a stored proc in invalid if it contains a user defined type.

The tool generates the following query for a stored proc in my database:

```
SET FMTONLY OFF; SET FMTONLY ON;
EXEC [Products].[ShipGoodsOut] @carrier=null, @service=null, @trackingNumber=null, @goodsOutIds=null
SET FMTONLY OFF; SET FMTONLY OFF;
```

The last parameter is a user defined table type:

```
CREATE TYPE [dbo].[Ids] AS TABLE(
[Id] [int] NOT NULL
)
```

Running the generated query gives the following error:

> Msg 206, Level 16, State 2, Procedure ShipGoodsOut, Line 13
Operand type clash: NULL is incompatible with Ids


That causes an exception and means the code required to populate the return model is never generated and so it fallsback to the code required to set the out parameter.

If I change the query such that it looks like this:

```
SET FMTONLY OFF; SET FMTONLY ON;
DECLARE @carrier varchar(25)
DECLARE @service varchar(25)
DECLARE @trackingNumber varchar(25)
DECLARE @goodsOutIds [dbo].[Ids]
EXEC [Products].[ShipGoodsOut] @carrier, @service, @trackingNumber, @goodsOutIds
SET FMTONLY OFF; SET FMTONLY OFF;
```

It works fine.

Commented Issue: ReadStoredProcReturnObject throws an exception if a parameter contains a user defined type [173]

$
0
0
Hi,

The generated query used to work out the return model of a stored proc in invalid if it contains a user defined type.

The tool generates the following query for a stored proc in my database:

```
SET FMTONLY OFF; SET FMTONLY ON;
EXEC [Products].[ShipGoodsOut] @carrier=null, @service=null, @trackingNumber=null, @goodsOutIds=null
SET FMTONLY OFF; SET FMTONLY OFF;
```

The last parameter is a user defined table type:

```
CREATE TYPE [dbo].[Ids] AS TABLE(
[Id] [int] NOT NULL
)
```

Running the generated query gives the following error:

> Msg 206, Level 16, State 2, Procedure ShipGoodsOut, Line 13
Operand type clash: NULL is incompatible with Ids


That causes an exception and means the code required to populate the return model is never generated and so it fallsback to the code required to set the out parameter.

If I change the query such that it looks like this:

```
SET FMTONLY OFF; SET FMTONLY ON;
DECLARE @carrier varchar(25)
DECLARE @service varchar(25)
DECLARE @trackingNumber varchar(25)
DECLARE @goodsOutIds [dbo].[Ids]
EXEC [Products].[ShipGoodsOut] @carrier, @service, @trackingNumber, @goodsOutIds
SET FMTONLY OFF; SET FMTONLY OFF;
```

It works fine.
Comments: Thanks Andy

Created Unassigned: bit with string as default value always returns true [177]

$
0
0
It is possible to use both the integer values _0_ or _1_ __AND__ the string values _true_ or _false_ as default values for the bit data type in SQL Server.

The T4 template does not handle the string values:

```
Default = (Default == "0") ? "false" : "true";
```
_(EF.Reverse.POCO.Core.ttinclude - line number 823)_

As described, this will return _true_, because the string value is not handled. I would suggest changing to something like this

```
Default = (Default == "0" || Default == "false") ? "false" : "true";
```

/Thomas

Edited Unassigned: bit with string as default value always returns true [177]

$
0
0
It is possible to use both the integer values _0_ or _1_ __AND__ the string values _true_ or _false_ as default values for the bit data type in SQL Server.

The T4 template does not handle the string values:

```
Default = (Default == "0") ? "false" : "true";
```
_(EF.Reverse.POCO.Core.ttinclude - line number 823)_

As described, this will return _true_, because the string value is not handled. I would suggest changing to something like this

```
Default = (Default == "0" || Default == "\"false\"") ? "false" : "true";
```

/Thomas


Source code checked in, #261d26c71ed0

$
0
0
Case 173. ReadStoredProcReturnObject throws an exception if a parameter contains a user defined type. Thanks to AndyGJP.

Edited Issue: ReadStoredProcReturnObject throws an exception if a parameter contains a user defined type [173]

$
0
0
Hi,

The generated query used to work out the return model of a stored proc in invalid if it contains a user defined type.

The tool generates the following query for a stored proc in my database:

```
SET FMTONLY OFF; SET FMTONLY ON;
EXEC [Products].[ShipGoodsOut] @carrier=null, @service=null, @trackingNumber=null, @goodsOutIds=null
SET FMTONLY OFF; SET FMTONLY OFF;
```

The last parameter is a user defined table type:

```
CREATE TYPE [dbo].[Ids] AS TABLE(
[Id] [int] NOT NULL
)
```

Running the generated query gives the following error:

> Msg 206, Level 16, State 2, Procedure ShipGoodsOut, Line 13
Operand type clash: NULL is incompatible with Ids


That causes an exception and means the code required to populate the return model is never generated and so it fallsback to the code required to set the out parameter.

If I change the query such that it looks like this:

```
SET FMTONLY OFF; SET FMTONLY ON;
DECLARE @carrier varchar(25)
DECLARE @service varchar(25)
DECLARE @trackingNumber varchar(25)
DECLARE @goodsOutIds [dbo].[Ids]
EXEC [Products].[ShipGoodsOut] @carrier, @service, @trackingNumber, @goodsOutIds
SET FMTONLY OFF; SET FMTONLY OFF;
```

It works fine.

Commented Issue: ReadStoredProcReturnObject throws an exception if a parameter contains a user defined type [173]

$
0
0
Hi,

The generated query used to work out the return model of a stored proc in invalid if it contains a user defined type.

The tool generates the following query for a stored proc in my database:

```
SET FMTONLY OFF; SET FMTONLY ON;
EXEC [Products].[ShipGoodsOut] @carrier=null, @service=null, @trackingNumber=null, @goodsOutIds=null
SET FMTONLY OFF; SET FMTONLY OFF;
```

The last parameter is a user defined table type:

```
CREATE TYPE [dbo].[Ids] AS TABLE(
[Id] [int] NOT NULL
)
```

Running the generated query gives the following error:

> Msg 206, Level 16, State 2, Procedure ShipGoodsOut, Line 13
Operand type clash: NULL is incompatible with Ids


That causes an exception and means the code required to populate the return model is never generated and so it fallsback to the code required to set the out parameter.

If I change the query such that it looks like this:

```
SET FMTONLY OFF; SET FMTONLY ON;
DECLARE @carrier varchar(25)
DECLARE @service varchar(25)
DECLARE @trackingNumber varchar(25)
DECLARE @goodsOutIds [dbo].[Ids]
EXEC [Products].[ShipGoodsOut] @carrier, @service, @trackingNumber, @goodsOutIds
SET FMTONLY OFF; SET FMTONLY OFF;
```

It works fine.
Comments: Hi Andy, Can you double check the latest source code to make sure it works for you. See this [changeset](https://efreversepoco.codeplex.com/SourceControl/changeset/261d26c71ed0).

New Post: add hasoptional relationship which doesn't exist in DB

$
0
0
Hi Jeff,

You do indeed seem to be missing a FK in your database. I looks like one was manually added to the EDMX, but was never created within the database.

The simple answer is to create a SQL patch, which adds the missing FK in the database. Then simply save your database.tt file to reverse engineer it. However you said you can't do this, so I'm wondering if you are using migrations, and no longer need to reverse engineer the database anymore.

Anyway, in order for you to fix this you need to edit the column.ConfigFk field.
Something like:
    UpdateColumn = (Column column, Table table) => 
    {
        if (table.NameHumanCase == "EntryLog" && column.NameHumanCase == "LogEntryId")
        {
            column.ConfigFk.Add("HasOptional(a => a.ContactedLogEntryDetail).WithRequiredDependent(b => b.LogEntryId)");
        }
        
        // Perform Enum property type replacement
        var enumDefinition = EnumsDefinitions.FirstOrDefault(e =>
            (e.Schema.ToLowerInvariant() == table.Schema.ToLowerInvariant()) &&
            (e.Table == table.Name || e.Table == table.NameHumanCase) &&
            (e.Column == column.Name || e.Column == column.NameHumanCase));

        if (enumDefinition != null)
            column.PropertyType = enumDefinition.EnumType;
        
        return column;
    };
I'm guessing the correct ConfigFk entry you need, but I'm sure you could set the right value.

New Post: table specifies primary key different from base table

$
0
0
In UpdateColumn function, add
if (table.NameHumanCase == "AWCase" && column.NameHumanCase == "CaseId")
    column.Hidden = true;
Viewing all 1642 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>