Im using win10, vs2017.
I created a new project, then added nuget "System.Data.SQLite".
Next, I installed "sqlite-netFx46-setup-bundle-x86-2015-1.0.105.2.exe" from system.data.sqlite.org with fullInstall options and checkboxes.
I rebooted the PC.
Then in the Visual Studio Server Explorer, I connected a new SQLite Database.
Further added "ADO .Net Entity Date Model", added Entity and used "Generate DB from model"
Im getting this error:
App.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v13.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="System.Data.SQLite.EF6" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
</providers>
</entityFramework>
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SQLite.EF6" />
<add name="SQLite Data Provider (Entity Framework 6)" invariant="System.Data.SQLite.EF6" description=".NET Framework Data Provider for SQLite (Entity Framework 6)" type="System.Data.SQLite.EF6.SQLiteProviderFactory, System.Data.SQLite.EF6" />
<remove invariant="System.Data.SQLite" />
<add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".NET Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" />
</DbProviderFactories>
</system.data>
<connectionStrings>
<add name="mainEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SQLite.EF6;provider connection string='data source="C:\Users\User\Documents\Visual Studio Projects\DeleteThis\Test.db";version=3'" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
SSDLToSQL10.tt:
<#
//---------------------------------------------------------------------
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
//---------------------------------------------------------------------
// This T4 template generates T-SQL from an instance of
// System.Data.Metadata.Edm.StoreItemCollection, an object representation
// of the SSDL. This T-SQL is compatible with SQL 2012, 2008, 2005, CE, and Azure databases.
//---------------------------------------------------------------------
// Note: We will resolve all paths in assembly directives at runtime, taking
// macros and environment variables into account (e.g. $(ProjectDir), $(DevEnvDir) etc.)
#>
<## assembly name="System.Core" #>
<## assembly name="$(DevEnvDir)..\IDE\Microsoft.Data.Entity.Design.DatabaseGeneration.dll"#>
<## assembly name="$(DevEnvDir)..\IDE\EntityFramework.dll"#>
<## assembly name="$(DevEnvDir)..\IDE\EntityFramework.SqlServer.dll" #>
<## assembly name="$(DevEnvDir)..\IDE\EntityFramework.SqlServerCompact.dll" #>
<## import namespace="System.Linq" #>
<## import namespace="System.Text" #>
<## import namespace="System.Collections.Generic" #>
<## import namespace="System.Data.Entity" #>
<## import namespace="System.Data.Entity.Core.Metadata.Edm" #>
<## import namespace="Microsoft.Data.Entity.Design.DatabaseGeneration" #>
<## import namespace="System.Runtime.Remoting.Messaging" #>
<## import namespace="System.Text.RegularExpressions" #>
<## template language="C#" debug="true" hostspecific="true" #>
<## include file="GenerateTSQL.Utility.ttinclude"#>
<## output extension = ".sql" #>
<#
// +++++++++++++++++++++++++++++++++++++++++++++++++
// Setup for the template (initializing variables, etc.)
// +++++++++++++++++++++++++++++++++++++++++++++++++
string databaseName = this.GetInput<string>(EdmParameterBag.ParameterName.DatabaseName.ToString());
string edmxPath = this.GetInput<string>(EdmParameterBag.ParameterName.EdmxPath.ToString());
Version targetVersion = this.GetInput<Version>(EdmParameterBag.ParameterName.TargetVersion.ToString());
DbConfiguration.SetConfiguration(new TemplateDbConfiguration());
if (false == InitializeAndValidateExistingStore())
{
#>
-- Warning: There were errors validating the existing SSDL. Drop statements
-- will not be generated.
<#
}
#>
-- --------------------------------------------------
<#
if (this.IsSQLCE) {
#>
-- Entity Designer DDL Script for SQL Server Compact Edition
<#
} else {
#>
-- Entity Designer DDL Script for SQL Server 2005, 2008, 2012 and Azure
<#
}
#>
-- --------------------------------------------------
-- Date Created: <#=DateTime.Now#>
<#
if (!String.IsNullOrEmpty(edmxPath))
{
#>
-- Generated from EDMX file: <#=Id(edmxPath)#>
<#
}
#>
-- --------------------------------------------------
<# if (!this.IsSQLCE)
{
#>
SET QUOTED_IDENTIFIER OFF;
GO
<# if (!String.IsNullOrEmpty(databaseName))
{
#>
USE [<#=Id(databaseName)#>];
GO
<#
}
foreach (string unescapedSchemaName in (from es in Store.GetAllEntitySets() select es.GetSchemaName()).Distinct())
{
#>
IF SCHEMA_ID(N'<#=Lit(unescapedSchemaName)#>') IS NULL EXECUTE(N'CREATE SCHEMA [<#=Id(unescapedSchemaName)#>]');
<#
}
#>
GO
<# } #>
-- --------------------------------------------------
-- Dropping existing FOREIGN KEY constraints
<# if (this.IsSQLCE)
{
#>
-- NOTE: if the constraint does not exist, an ignorable error will be reported.
<# } #>
-- --------------------------------------------------
<#
foreach (AssociationSet associationSet in ExistingStore.GetAllAssociationSets())
{
ReferentialConstraint constraint = associationSet.ElementType.ReferentialConstraints.Single();
string constraintName = Id(WriteFKConstraintName(constraint));
AssociationSetEnd dependentSetEnd = associationSet.AssociationSetEnds.Where(ase => ase.CorrespondingAssociationEndMember == constraint.ToRole).Single();
string schemaName = Id(dependentSetEnd.EntitySet.GetSchemaName());
string dependentTableName = Id(dependentSetEnd.EntitySet.GetTableName());
if (!this.IsSQLCE)
{
#>
IF OBJECT_ID(N'[<#=Lit(schemaName)#>].[<#=Lit(constraintName)#>]', 'F') IS NOT NULL
<# } #>
ALTER TABLE <# if (!IsSQLCE) {#>[<#=schemaName#>].<#}#>[<#=dependentTableName#>] DROP CONSTRAINT [<#=constraintName#>];
GO
<#
}
#>
-- --------------------------------------------------
-- Dropping existing tables
<# if (this.IsSQLCE)
{
#>
-- NOTE: if the table does not exist, an ignorable error will be reported.
<# } #>
-- --------------------------------------------------
<#
foreach (EntitySet entitySet in ExistingStore.GetAllEntitySets())
{
string schemaName = Id(entitySet.GetSchemaName());
string tableName = Id(entitySet.GetTableName());
if (!this.IsSQLCE)
{
#>
IF OBJECT_ID(N'[<#=Lit(schemaName)#>].[<#=Lit(tableName)#>]', 'U') IS NOT NULL
<# } #>
DROP TABLE <# if (!IsSQLCE) {#>[<#=schemaName#>].<#}#>[<#=tableName#>];
GO
<#
}
#>
-- --------------------------------------------------
-- Creating all tables
-- --------------------------------------------------
<#
foreach (EntitySet entitySet in Store.GetAllEntitySets())
{
string schemaName = Id(entitySet.GetSchemaName());
string tableName = Id(entitySet.GetTableName());
#>
-- Creating table '<#=tableName#>'
CREATE TABLE <# if (!IsSQLCE) {#>[<#=schemaName#>].<#}#>[<#=tableName#>] (
<#
for (int p = 0; p < entitySet.ElementType.Properties.Count; p++)
{
EdmProperty prop = entitySet.ElementType.Properties[p];
#>
[<#=Id(prop.Name)#>] <#=prop.ToStoreType()#> <#=WriteIdentity(prop, targetVersion)#> <#=WriteNullable(prop.Nullable)#><#=(p < entitySet.ElementType.Properties.Count - 1) ? "," : ""#>
<#
}
#>
);
GO
<#
}
#>
-- --------------------------------------------------
-- Creating all PRIMARY KEY constraints
-- --------------------------------------------------
<#
foreach (EntitySet entitySet in Store.GetAllEntitySets())
{
string schemaName = Id(entitySet.GetSchemaName());
string tableName = Id(entitySet.GetTableName());
#>
-- Creating primary key on <#=WriteColumns(entitySet.ElementType.GetKeyProperties(), ',')#> in table '<#=tableName#>'
ALTER TABLE <# if (!IsSQLCE) {#>[<#=schemaName#>].<#}#>[<#=tableName#>]
ADD CONSTRAINT [PK_<#=tableName#>]
PRIMARY KEY <# if (!IsSQLCE) {#>CLUSTERED <#}#>(<#=WriteColumns(entitySet.ElementType.GetKeyProperties(), ',')#> <# if (!IsSQLCE) {#>ASC<#}#>);
GO
<#
}
#>
-- --------------------------------------------------
-- Creating all FOREIGN KEY constraints
-- --------------------------------------------------
<#
foreach (AssociationSet associationSet in Store.GetAllAssociationSets())
{
ReferentialConstraint constraint = associationSet.ElementType.ReferentialConstraints.Single();
AssociationSetEnd dependentSetEnd = associationSet.AssociationSetEnds.Where(ase => ase.CorrespondingAssociationEndMember == constraint.ToRole).Single();
AssociationSetEnd principalSetEnd = associationSet.AssociationSetEnds.Where(ase => ase.CorrespondingAssociationEndMember == constraint.FromRole).Single();
string schemaName = Id(dependentSetEnd.EntitySet.GetSchemaName());
string dependentTableName = Id(dependentSetEnd.EntitySet.GetTableName());
string principalTableName = Id(principalSetEnd.EntitySet.GetTableName());
#>
-- Creating foreign key on <#=WriteColumns(constraint.ToProperties, ',')#> in table '<#=dependentTableName#>'
ALTER TABLE <#if (!IsSQLCE) {#>[<#=schemaName#>].<#}#>[<#=dependentTableName#>]
ADD CONSTRAINT [<#=WriteFKConstraintName(constraint)#>]
FOREIGN KEY (<#=WriteColumns(constraint.ToProperties, ',')#>)
REFERENCES <# if (!IsSQLCE) {#>[<#=schemaName#>].<#}#>[<#=principalTableName#>]
(<#=WriteColumns(constraint.FromProperties, ',')#>)
ON DELETE <#=GetDeleteAction(constraint)#> ON UPDATE NO ACTION;
GO
<#
// if the foreign keys are part of the primary key on the dependent end, then we should not add a constraint.
if (!dependentSetEnd.EntitySet.ElementType.GetKeyProperties().Take(constraint.ToProperties.Count()).OrderBy(r => r.Name).SequenceEqual(constraint.ToProperties.OrderBy(r => r.Name)))
{
#>
-- Creating non-clustered index for FOREIGN KEY '<#=WriteFKConstraintName(constraint)#>'
CREATE INDEX [IX_<#=WriteFKConstraintName(constraint)#>]
ON <#if (!IsSQLCE) {#>[<#=schemaName#>].<#}#>[<#=dependentTableName#>]
(<#=WriteColumns(constraint.ToProperties, ',')#>);
GO
<#
}
}
#>
-- --------------------------------------------------
-- Script has ended
-- --------------------------------------------------
This feature does not work for SQLite, as hinted at in the tt file:
<#
if (this.IsSQLCE) {
#>
-- Entity Designer DDL Script for SQL Server Compact Edition
<#
} else {
#>
-- Entity Designer DDL Script for SQL Server 2005, 2008, 2012 and Azure
<#
}
#>
Related
I'm getting random errors in some queries using Npgsql.
Here is the stack trace:
at NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Loader\Loader.cs:line 1597
at NHibernate.Loader.Loader.ListIgnoreQueryCache(ISessionImplementor session, QueryParameters queryParameters) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Loader\Loader.cs:line 1497
at NHibernate.Loader.Loader.List(ISessionImplementor session, QueryParameters queryParameters, ISet`1 querySpaces, IType[] resultTypes) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Loader\Loader.cs:line 1487
at NHibernate.Impl.SessionImpl.List(CriteriaImpl criteria, IList results) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Impl\SessionImpl.cs:line 1955
at NHibernate.Impl.CriteriaImpl.List(IList results) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Impl\CriteriaImpl.cs:line 265
at NHibernate.Impl.CriteriaImpl.List[T]() in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Impl\CriteriaImpl.cs:line 276
at LAVASPORT.DAO.MigrarCadeteDAO.findByCompania(Compania compania, String conexion, DateTime fechainicial, DateTime fechafinal) in D:\Aplicaciones\LavaSport\LAVASPORT\DAO\MigrarCadeteDAO.cs:line 125
And here is the message
InnerException = {"57014: canceling statement due to statement timeout"}
I'm not getting this exceptions all the time, just 1 or 2 times at day. The query in special that most send the exception is a high volume query.
Here is the query:
public IList<Cadete> findByCompania(Compania compania, String conexion,DateTime fechainicial,DateTime fechafinal)
{
try
{
DateTime fechaini = new DateTime(fechainicial.Year, fechainicial.Month, fechainicial.Day);
DateTime fechafin = new DateTime(fechafinal.Year, fechafinal.Month, fechafinal.Day);
var nhConfig = new Configuration().Configure(conexion);
var sessionFactory = nhConfig.BuildSessionFactory();
var session = sessionFactory.OpenSession();
session.BeginTransaction();
var query = session.CreateCriteria<Cadete>();
query.CreateAlias("compania", "compania");
query.Add(Restrictions.Eq("compania.id", compania.id))
.Add(Restrictions.Lt("fechaIngreso", fechafin))
.Add(Restrictions.Ge("fechaIngreso",fechaini));
IList<Cadete> cadetes = query.List<Cadete>();
return cadetes;
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex.Message);
}
return null;
}
This are my NHibernate configuration and my web config file:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" >
<session-factory name="LAVASPORT">
<property name="connection.driver_class">NHibernate.Driver.NpgsqlDriver</property>
<property name="connection.connection_string">
Server=localhost;database=LAVASPORT;user id=postgres;password=admin;MaxPoolSize=500;TimeOut=1000;
</property>
<property name="dialect">NHibernate.Dialect.PostgreSQLDialect</property>
<property name="show_sql">true</property>
<property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>
<mapping assembly="LAVASPORT"/>
</session-factory>
</hibernate-configuration>
If I increase the timeout to more than 1000, I get errors on connections every time.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
<section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"></section>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --></configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1"/>
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0"/>
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
</providers>
</entityFramework>
<system.transactions>
<defaultSettings timeout="10:00:00" />
</system.transactions>
</configuration>
I would really appreciate any help.
First, note that the Timeout connection string parameter manages connection timeouts (i.e. NpgsqlConnection.Open()) rather than command execution timeout. Defaul command execution timeout is managed via the Command Timeout connection string parameter.
Beyond that, it seems like your commands are simply timing out. Since the default command timeout is 30 seconds, it would seem you have some serious performance issue with your queries, your database index, or something else. You need to carefully analyze the SQL being created by NHibernate and how it's executed by PostgreSQL.
When I use GetDropAndCreateDdl to generate CREATE scripts for tables, I get datatypes for columns that are different than what the datatypes actually are.
This results in a package validation error that "the error output has properties that do not match the properties of its corresponding data source column" and a validation status of "VS_NEEDSNEWMETADATA".
If I right-click the connection source, select Show Advanced Editor, and take a look at the Column Mappings, I can see that [Column1] in the Available External Columns list has a different Length than the datatype that was generated in the GetDropAndCreateDdl. I can delete and re-create the metadata mappings, but that is not a viable solution since there are many dataflow tasks.
How do I get GetDropAndCreateDdl to create the correct datatypes with correct lengths?
I am using ImportDB to get the list of tables, metadata, etc.
Environment.biml
<Biml xmlns="http://schemas.varigence.com/biml.xsd">
<Connections>
<OdbcConnection Name="OdbcSrc_DV" ConnectionString="Dsn=Source-32bit-test;" />
<OleDbConnection Name="OleDbDst_Staging" ConnectionString="Provider=SQLNCLI11;Server=SQL-DEV;Initial Catalog=Source_Staging;Integrated Security=SSPI;" />
</Connections>
<Databases>
<Database Name="Source" ConnectionName="OdbcSrc_DV" />
<Database Name="Source_Staging" ConnectionName="OleDbDst_Staging" />
</Databases>
<Schemas>
<Schema Name="dbo" DatabaseName="Source" />
<Schema Name="dbo" DatabaseName="Source_Staging" />
</Schemas>
</Biml>
CreateTableMetadata.biml
<## import namespace="System.Data" #>
<## import namespace="Varigence.Biml.CoreLowerer.SchemaManagement" #>
<#
var sourceConnection = RootNode.DbConnections["OdbcSrc_DV"];
var importResult = sourceConnection.ImportDB("", "", ImportOptions.ExcludeForeignKey | ImportOptions.ExcludeColumnDefault | ImportOptions.ExcludeViews);
var tableNamesToImport = new List<string>() { "Test_Table" };
#>
<Biml xmlns="http://schemas.varigence.com/biml.xsd">
<Tables>
<# foreach (var table in importResult.TableNodes.Where(item => tableNamesToImport.Contains(item.Name)).OrderBy(item => item.Name)) { #>
<Table Name="<#=table.Name#>" SchemaName="Source.dbo">
<Columns>
<#=table.Columns.GetBiml()#>
</Columns>
<Annotations>
<Annotation AnnotationType="Tag" Tag="SourceSchemaQualifiedName"><#=table.SchemaQualifiedName#></Annotation>
</Annotations>
</Table>
<# } #>
</Tables>
</Biml>
DeployTargetTables.biml
<## template tier="2" #>
<Biml xmlns="http://schemas.varigence.com/biml.xsd">
<Packages>
<Package Name="MasterTableDeploy" ConstraintMode="Parallel">
<Tasks>
<# foreach (var table in RootNode.Tables) { #>
<ExecuteSQL Name="SQL CREATE <#=table.Name#>" ConnectionName="OleDbDst_Staging">
<DirectInput><#=table.GetDropAndCreateDdl()#></DirectInput>
</ExecuteSQL>
<# } #>
</Tasks>
</Package>
</Packages>
</Biml>
CreateLoadPackages.biml
<## template tier="2" #>
<Biml xmlns="http://schemas.varigence.com/biml.xsd">
<Packages>
<Package Name="Copy Data" ConstraintMode="Parallel">
<Tasks>
<# foreach (var table in RootNode.Tables) { #>
<ExecuteSQL Name="SQL TRUNCATE <#=table.Name#>" ConnectionName="OleDbDst_Staging">
<DirectInput>TRUNCATE TABLE <#=table.Name#></DirectInput>
</ExecuteSQL>
<Dataflow Name="DFT LOAD <#=table.Schema.Name#>_<#=table.Name#>">
<PrecedenceConstraints>
<Inputs>
<Input OutputPathName="SQL TRUNCATE <#=table.Name#>.Output" />
</Inputs>
</PrecedenceConstraints>
<Transformations>
<OdbcSource Name="ODBC_SRC <#=table.Name#>" Connection="OdbcSrc_DV">
<DirectInput>SELECT <#=table.GetColumnList()#> FROM <#=table.GetTag("SourceSchemaQualifiedName")#></DirectInput>
</OdbcSource>
<OleDbDestination Name="ODBC_DST <#=table.Name#>" ConnectionName="OleDbDst_Staging">
<TableOutput TableName="<#=table.ScopedName#>" />
</OleDbDestination>
</Transformations>
</Dataflow>
<# } #>
</Tasks>
</Package>
</Packages>
</Biml>
Here is the script that gets created from the ODBC source -
And here are the results from INFORMATION_SCHEMA.COLUMNS for the same table -
Have you tried using the newer method: GetDatabaseSchema? I've found it to be much more reliable across different connection types.
http://www.cathrinewilhelmsen.net/2015/07/12/biml-extension-methods-getdatabaseschema/
I have a CodeFluent Entities Model such as:
<cf:project defaultNamespace="S5T" xmlns:cf="http://www.softfluent.com/codefluent/2005/1" xmlns:cfx="http://www.softfluent.com/codefluent/modeler/2008/1" xmlns:cfmy="http://www.softfluent.com/codefluent/producers.mysql/2012/1" xmlns:cfom="http://www.softfluent.com/codefluent/producers.model/2005/1" xmlns:cfasp="http://www.softfluent.com/codefluent/producers.aspnet/2011/1" xmlns:cfaz="http://www.softfluent.com/codefluent/producers.sqlazure/2011/1" xmlns:cfps="http://www.softfluent.com/codefluent/producers.sqlserver/2005/1" defaultKeyPropertyTypeName="long" maxParameterNameLength="62" defaultConcurrencyMode="None" persistencePropertyNameFormat="{1}" defaultMethodAllowDynamicSort="false" defaultProducerProductionFlags="Default, Overwrite, RemoveDates" defaultMethodDistinct="false" createDefaultMethodForms="true" createDefaultApplication="false" createDefaultHints="false" productionFlags="Default, Overwrite, RemoveDates">
<cf:import path="Default.Surface.cfp" />
<cf:producer name="SQL Server" typeName="CodeFluent.Producers.SqlServer.SqlServerProducer, CodeFluent.Producers.SqlServer">
<cf:configuration produceViews="true" targetDirectory="..\Model7Bom\Persistence" connectionString="Server=MY-MACHINE\SQLEXPRESS;Database=model7;Integrated Security=true;Application Name=S5T;Password=MyPassword;User ID=MyUser" cfx:targetProject="..\Model7Bom\Model7Bom.vbproj" cfx:targetProjectLayout="Update, DontRemove" />
</cf:producer>
<cf:entity name="User" namespace="S5T">
<cf:property name="Id" key="true" cfps:hint="CLUSTERED" />
<cf:property name="Name" />
<cf:property name="Roles" typeName="{0}.RoleCollection" relationPropertyName="Users" />
</cf:entity>
<cf:entity name="Role" namespace="S5T">
<cf:property name="Id" key="true" cfps:hint="CLUSTERED" />
<cf:property name="Name" />
<cf:property name="Users" typeName="{0}.UserCollection" relationPropertyName="Roles" />
</cf:entity>
</cf:project>
I could sucessfully decorate the cf:property name="Id" on both entities with cfps:hint="CLUSTERED". This got me Sql Server producer to correctly output
CONSTRAINT [PK_Use_Id_Use] PRIMARY KEY CLUSTERED
CONSTRAINT [PK_Rol_Id_Rol] PRIMARY KEY CLUSTERED
as opposed to default NONCLUSTERED.
How can I accomplish that with the THIRD TABLE generated by the model, to accomodate the many to many relationship?
By default, the table creation generated snippet is such as:
CREATE TABLE [dbo].[Role_Users_User_Roles] (
[Id] [bigint] NOT NULL,
[Id2] [bigint] NOT NULL,
CONSTRAINT [PK_Roe_Id_Id2_Roe] PRIMARY KEY NONCLUSTERED
(
[Id],
[Id2]
) ON [PRIMARY]
)
However, if I decorate both properties with cfps:hint="CLUSTERED" as in:
cf:property name="Roles" typeName="{0}.RoleCollection" relationPropertyName="Users" cfps:hint="CLUSTERED" /
cf:property name="Users" typeName="{0}.UserCollection" relationPropertyName="Roles" cfps:hint="CLUSTERED" /
I get a snippet generated with PRIMARY KEY CLUSTERED for the PK in TABLE [dbo].[Role_Users_User_Roles], BUT, in addition, I get an UNDESIRED effect of having an incorrect script generated for adding relations (generated filename ...relations_add.sql), such as:
ALTER TABLE [dbo].[Role_Users_User_Roles] WITH NOCHECK ADD CONSTRAINT [FK_Roe_Id_Id_Rol] FOREIGN KEY (
[Id]
) REFERENCES [dbo].[Role](
[Id]
) CLUSTERED
Along with the error from Sql Server:
Error 3 SQL80001: Incorrect syntax near 'CLUSTERED'.
And CodeFluent Producer Error:
CodeFluentRuntimeDatabaseException: CF4116: Execution of file ...path..._relations_add.sql statement at line 2
I need all three PKs CLUSTERED in the three tables generated, but not the side effect of syntax error for generating the relations.
This is not supported out-of-the-box. The hint declared on the a relation is rarely used, more meant as a Foreign Key hint than a column hint. There are several options you can use to do this.
The easiest is to use a post-generation .SQL script to add the clustered setting manually. This is described here: How to: Execute custom T-SQL scripts with the Microsoft SQL Server producer.
You could also use the Patch Producer to remove the CLUSTERED word from the file once it has been created : Patch Producer
Otherwise, here is another solution that involves an aspect I've written as a sample here. You can save the following piece of XML as a file, and reference it as an aspect in your model.
This aspect will add the CLUSTERED hint to primary keys of all Many To Many tables inferred from entities that have CLUSTERED keys. It will add the hint before the table scripts are created and ran, and will remove it after (so it won't end up in the relations_add script).
<cf:project xmlns:cf="http://www.softfluent.com/codefluent/2005/1">
<!-- assembly references -->
<?code #reference name="CodeFluent.Producers.SqlServer.dll" ?>
<?code #reference name="CodeFluent.Runtime.Database.dll" ?>
<!-- namespace includes -->
<?code #namespace name="System" ?>
<?code #namespace name="System.Collections.Generic" ?>
<?code #namespace name="CodeFluent.Model.Code" ?>
<?code #namespace name="CodeFluent.Model.Persistence" ?>
<?code #namespace name="CodeFluent.Model.Code" ?>
<!-- add global code to listen to inference steps -->
<?code
Project.StepChanging += (sender1, e1) =>
{
if (e1.Step == ImportStep.End) // hook before production begins (end of inference pipeline)
{
var modifiedTables = ProjectHandler.AddClusteredHint(Project);
// get sql server producer and hook on production events
var sqlProducer = Project.Producers.GetProducerInstance<CodeFluent.Producers.SqlServer.SqlServerProducer>();
sqlProducer.Production += (sender, e) =>
{
// determine what SQL file has been created
// we want to remove hints once the table_diffs has been created, before relations_add is created
string script = e.GetDictionaryValue("filetype", null);
if (script == "TablesDiffsScript")
{
ProjectHandler.RemoveClusteredHint(modifiedTables);
}
};
}
};
?>
<!-- add member code to handle inference modification -->
<?code #member
public class ProjectHandler
{
public static IList<Table> AddClusteredHint(Project project)
{
var list = new List<Table>();
foreach (var table in project.Database.Tables)
{
// we're only interested by tables inferred from M:M relations
if (table.Relation == null || table.Relation.RelationType != RelationType.ManyToMany)
continue;
// check this table definition is ok for us
if (table.RelationKeyColumns.Count < 1 || table.RelationRelatedKeyColumns.Count < 1)
continue;
// check clustered is declared on both sides
string keyHint = GetSqlServerProducerHint(table.RelationKeyColumns[0].Property);
string relatedKeyHint = GetSqlServerProducerHint(table.RelationKeyColumns[0].Property);
if (keyHint.IndexOf("clustered", StringComparison.OrdinalIgnoreCase) < 0 ||
relatedKeyHint.IndexOf("clustered", StringComparison.OrdinalIgnoreCase) < 0)
continue;
// force hint now, we only need to do this on one of the keys, not all
table.PrimaryKey.Elements[0].SetAttribute("hint", CodeFluent.Producers.SqlServer.Constants.SqlServerProducerNamespaceUri, "clustered");
// remember this table
list.Add(table);
}
return list;
}
public static void RemoveClusteredHint(IEnumerable<Table> list)
{
foreach (var table in list)
{
table.PrimaryKey.Elements[0].RemoveAttribute("hint", CodeFluent.Producers.SqlServer.Constants.SqlServerProducerNamespaceUri);
}
}
// helper method to read XML element's hint attribute in the SQL Server Producer namespace
private static string GetSqlServerProducerHint(Node node)
{
if (node == null)
return null;
return node.GetAttributeValue<string>("hint", CodeFluent.Producers.SqlServer.Constants.SqlServerProducerNamespaceUri, null);
}
}
?>
</cf:project>
I'd like to use PowerShell as part of our automated build process to update an App.config file while deploying into our test environment. How can I do this?
Given this sample App.config: C:\Sample\App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="dbConnectionString"
connectionString="Data Source=(local);Initial Catalog=Northwind;Integrated Security=True"/>
</connectionStrings>
</configuration>
The following script, C:\Sample\Script.ps1, will read and write a setting:
# get the directory of this script file
$currentDirectory = [IO.Path]::GetDirectoryName($MyInvocation.MyCommand.Path)
# get the full path and file name of the App.config file in the same directory as this script
$appConfigFile = [IO.Path]::Combine($currentDirectory, 'App.config')
# initialize the xml object
$appConfig = New-Object XML
# load the config file as an xml object
$appConfig.Load($appConfigFile)
# iterate over the settings
foreach($connectionString in $appConfig.configuration.connectionStrings.add)
{
# write the name to the console
'name: ' + $connectionString.name
# write the connection string to the console
'connectionString: ' + $connectionString.connectionString
# change the connection string
$connectionString.connectionString = 'Data Source=(local);Initial Catalog=MyDB;Integrated Security=True'
}
# save the updated config file
$appConfig.Save($appConfigFile)
Execute the script:
PS C:\Sample> .\Script.ps1
Output:
name: dbConnectionString
connectionString: Data Source=(local);Initial Catalog=Northwind;Integrated Security=True
Updated C:\Sample\App.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="dbConnectionString"
connectionString="Data Source=(local);Initial Catalog=MyDB;Integrated Security=True" />
</connectionStrings>
</configuration>
The code can be much more shorter (based on Robin's app.config):
$appConfig = [xml](cat D:\temp\App.config)
$appConfig.configuration.connectionStrings.add | foreach {
$_.connectionString = "your connection string"
}
$appConfig.Save("D:\temp\App.config")
I am trying to run a method in C# Interactive that return some data from local db using Entity Framework. But it return an error saying that the connection string named 'InteractiveConsoleDBEntities' could be found in the application config file.
I am using data base first.
I use the option "Initialize Interactive with project" to start with C# Interactive.
Here is the details...
Commands in Interactive Console
#r "C:\Users\Path\InteractiveConsole\packages\EntityFramework.5.0.0\lib\net45\EntityFramework.dll"
#r "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.dll"
#r "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.ComponentModel.DataAnnotations.dll"
#r "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.Core.dll"
#r "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.Data.Entity.dll"
#r "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.Runtime.Serialization.dll"
#r "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.Security.dll"
#r "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.Xml.Linq.dll"
#r "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.Data.DataSetExtensions.dll"
#r "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\Microsoft.CSharp.dll"
#r "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.Data.dll"
#r "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.Net.Http.dll"
#r "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.Xml.dll"
#r "InteractiveConsole.exe"
using InteractiveConsole;
using InteractiveConsole.Model;
using InteractiveConsole.DAL;
var context = new InteractiveConsoleDBEntities();
context.Employees.ToList();
Then I get the error
No connection string named 'InteractiveConsoleDBEntities' could be found in the application config file.
+ System.Data.Entity.Internal.LazyInternalConnection.get_ConnectionHasModel()
+ System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
+ System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(System.Type)
+ InternalSet<TEntity>.Initialize()
+ InternalSet<TEntity>.Include(string)
+ DbQuery<TResult>.Include(string)
+ System.Data.Entity.DbExtensions.Include<T>(IQueryable<T>, string)
+ System.Data.Entity.DbExtensions.Include<T, TProperty>(IQueryable<T>, Expression<Func<T, TProperty>>)
+ InteractiveConsole.DAL.EmployeeDAL.GetEmployeeList()
The App.config file
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v13.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
<connectionStrings>
<add name="InteractiveConsoleDBEntities" connectionString="metadata=res://*/Model.Model.csdl|res://*/Model.Model.ssdl|res://*/Model.Model.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDB)\MSSQLLocalDB;attachdbfilename=|DataDirectory|\DB\InteractiveConsoleDB.mdf;integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
The DbContext
namespace InteractiveConsole.Model
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class InteractiveConsoleDBEntities : DbContext
{
public InteractiveConsoleDBEntities()
: base("name=InteractiveConsoleDBEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<Employee> Employees { get; set; }
public DbSet<Person> People { get; set; }
}
}
The class with method
using System.Data.Entity;
namespace InteractiveConsole.DAL
{
public class EmployeeDAL
{
public static List<Employee> GetEmployeeList()
{
using (var context = new InteractiveConsoleDBEntities())
{
return context.Employees.Include(x => x.Person).ToList();
}
}
}
}
The same project in Immediate Window works fine
InteractiveConsole.DAL.EmployeeDAL.GetEmployeeList()
Count = 2
[0]: {System.Data.Entity.DynamicProxies.Employee_0D99EB301BB74EDFF2203163D6E8A936C70F24995F1639BF58D81DCCA671DEC0}
[1]: {System.Data.Entity.DynamicProxies.Employee_0D99EB301BB74EDFF2203163D6E8A936C70F24995F1639BF58D81DCCA671DEC0}
Hope some one know what I doing wrong and can help me.
Thanks a lot
Struggled with this one for a while before I finally got it working.
Create a new partial class (for example named YourEntities.cs) with a new overload for your constructor that takes a connection string parameter (don't modify your existing class as it will be overwritten whenever you re-model the database):
using System.Data.Entity;
namespace YourNamespace.Models
{
public partial class YourEntities : DbContext
{
public YourEntities(string connectionString)
: base(connectionString)
{
}
}
}
Then, build your project, right click it and click "Initialize Interactive with Project". Open your web.config / app.config and copy the connection string to your clipboard.
In the interactive window, paste this replacing ConnStringHere with your connection string but don't hit enter:
var db = new YourNamespace.Models.YourEntities("ConnStringHere");
After you paste, replace " in the connection string with \" , go to the end of the line in C# interactive and hit enter.
Then you should be able to use db in your C# Interactive window it as if it were in your app:
Print(db.Employees.Count());
I realize this is old, but I found a way to make this work without changing my code, or creating any proxies or other work-around code. I was able to make this work by editing the config file for the interactive window, itself. See my answer in this post:
Project can't find my EF connection string in C# Interactive
You may have to add other config data, as well, if your app relies on it. Just adding the connection string was enough, for me.