I have an application which has three layers.I am using EntityFramework 6.1 and code first migrations using existing database.The three layers are given below:
1.Presententation Layer:ConceptuCodeFirstMigrationDemo
Simply a Console Application for simplicity
Data Layer Consists of Context and Initializer.The codes are given below:
namespace ConceptuCodeFirstMigrationDemo.Data.DataContext
{
using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using ConceptuCodeFirstMigrationDemo.Domain;
public partial class ConceptuContext : DbContext,IDisposable
{
public ConceptuContext()
: base("name=ConceptuContext")
{
}
public virtual DbSet<User> Users { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.WithRequired(e => e.User)
.HasForeignKey(e => e.CreatedBy)
.WillCascadeOnDelete(false);
}
}
}
ConceptuInitializer.Cs
namespace ConceptuCodeFirstMigrationDemo.Data.DataContext
{
public class ConceptuInitializer: System.Data.Entity.CreateDatabaseIfNotExists<ConceptuContext>
{
}
}
Appconfig:
<?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>
<entityFramework>
<contexts>
<context type="ConceptuCodeFirstMigrationDemo.Data.DataContext.ConceptuContext, ConceptuCodeFirstMigrationDemo.Data">
<databaseInitializer type="ConceptuCodeFirstMigrationDemo.Data.DataContext.ConceptuInitializer, ConceptuCodeFirstMigrationDemo.Data" />
</context>
</contexts>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<connectionStrings>
<add name="ConceptuContext" connectionString="data source=AMITABHA-PC;initial catalog=Conceptu;user id=sa;password=lovediya;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Domain Layer: Consists of entity class for example user
After writing a new class when I try to enable migrations using Enable-Migrations
showing
No context type was found in the assembly 'ConceptuCodeFirstMigrationDemo'.
After I tried the following command:
Enable-Migrations -ContextTypeName ConceptuCodeFirstMigrationDemo.Data.DataContext.ConceptuContext
this shows following error
The context type 'ConceptuCodeFirstMigrationDemo.Data.DataContext.ConceptuContext' was not found in the assembly 'ConceptuCodeFirstMigrationDemo'.
After I tried the following command
Enable-Migrations ConceptuCodeFirstMigrationDemo.Data.DataContext.ConceptuContext
It shows the following error
Enable-Migrations : A positional parameter cannot be found that accepts argument 'ConceptuCodeFirstMigrationDemo.Data.DataContext.Concept
uContext'.
At line:1 char:18
+ Enable-Migrations <<<< ConceptuCodeFirstMigrationDemo.Data.DataContext.ConceptuContext
+ CategoryInfo : InvalidArgument: (:) [Enable-Migrations], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Enable-Migrations
Try this.
Enable-Migrations -ContextTypeName ConceptuCodeFirstMigrationDemo.Data.DataContext.ConceptuContext -ProjectName ConceptuCodeFirstMigrationDemo
Related
I have an .Net MVC project with SSO working. The SSO config looks like this:
<system.identityModel>
<identityConfiguration saveBootstrapContext="true">
<caches>
<sessionSecurityTokenCache type="Vixion.IdentityModel.Cache.SharedSessionSecurityTokenCache, Vixion.IdentityModel.Cache">
<cacheServiceAddress url="http://tvwapps35434d.kpnis.nl:1008/SessionSecurityTokenCacheService.svc" />
</sessionSecurityTokenCache>
</caches>
<audienceUris>
<add value="http://localhost:24442/" />
</audienceUris>
<securityTokenHandlers>
<remove type="System.IdentityModel.Services.Tokens.MachineKeySessionSecurityTokenHandler, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<add type="System.IdentityModel.Tokens.SessionSecurityTokenHandler, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<add type="System.IdentityModel.Tokens.Saml2SecurityTokenHandler, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</securityTokenHandlers>
<certificateValidation certificateValidationMode="None" />
<issuerNameRegistry type="System.IdentityModel.Tokens.ValidatingIssuerNameRegistry, System.IdentityModel.Tokens.ValidatingIssuerNameRegistry">
<authority name="http://vix-make-o:8080">
<keys>
<add thumbprint="5137c779a1e77a0f4a78abd356b0238912637469" />
</keys>
<validIssuers>
<add name="http://vix-make-o:8080" />
</validIssuers>
</authority>
</issuerNameRegistry>
</identityConfiguration>
</system.identityModel>
<system.identityModel.services>
<federationConfiguration>
<cookieHandler requireSsl="false" path="/" />
<wsFederation passiveRedirectEnabled="true" issuer="http://vix-make-o:8080" realm="http://localhost:24442/" requireHttps="false" reply="http://localhost:24442/" />
</federationConfiguration>
</system.identityModel.services>
According to the example here:
https://github.com/Sustainsys/Saml2/tree/master/Sustainsys.Saml2.AspNetCore2
I write this code in a new .NetCore app:
services.AddIdentity<IdentityUser, IdentityRole>()
.AddDefaultTokenProviders();
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.Cookie.HttpOnly = true;
});
services.AddMvc()
.AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
services.AddAuthentication()
.AddSaml2(options =>
{
options.SPOptions.EntityId = new EntityId("http://vix-make-o:8080");
options.IdentityProviders.Add(
new IdentityProvider(
new EntityId("http://vix-make-o:8080/ws_saml_metadata"), options.SPOptions)
{
//LoadMetadata = true
});
});
app.UseAuthentication();
app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
When I start the app, the browser goes straight to the index page. No error, no nothing. When I check with SAML Chrome Panel it shows no traffic at all.
I do not expect my code working, but it should at least do something to give me a hint to how to go further.
Any suggestions are welcome.
Thank you.
S.
Remove the web.config content. It is not used with the ASP.NET Core module.
Set back the LoadMetadata flag, or add the necessary config manually.
Set Saml2 as the default challenge protocol for authentication.
Finally, add an [Authorize] attribute to your controllers that should require authentication to initiate the authentication process.
I am trying to do POC of switching from forms authentication in existing MVC 4 application to claims-based one, but cannot get custom authorize attribute working - have infinite redirect loop ending with known 'bad request' issue because of total cookie size...
And the reason - there is no authenticated identity (and correct Claims collection) in attribute context as I see it in debug despite I see successfully created identity with expected claims collection in SecurityTokenValidated handler.
So, it seems like it is somehow lost after OIDC middleware process it, and not unavailable in attribute context, therefore I cannot further check for 'role' claim.
Maybe I am missing something?
My OWIN Startup:
AntiForgeryConfig.UniqueClaimTypeIdentifier = "sub";
JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = CookieAuthenticationDefaults.AuthenticationType
});
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
AuthenticationType = "oidc",
//AuthenticationMode = AuthenticationMode.Active, // ? https://github.com/IdentityServer/IdentityServer3/issues/1963
Authority = OAuthServerUrl,
ClientId = "my_app",
RedirectUri = MyAppUrl,
ResponseType = "id_token token", //notice, if response type 'token' is requested, IdentityServer stops including the claims in the identity token, though we could set alwaysInclude=true for some scope claims (ex. for role)
Scope = "openid profile roles",
SignInAsAuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
PostLogoutRedirectUri = MyAppUrl,
Notifications = new OpenIdConnectAuthenticationNotifications
{
SecurityTokenValidated = n =>
{
var id = n.AuthenticationTicket.Identity;
//n.OwinContext.Authentication.SignIn(id);
//tried SignIn() explicitly, and even setting HttpContext.Current.User and Thread.CurrentPrincipal to n.AuthenticationTicket.Identity, but without luck
return Task.FromResult(0);
},
RedirectToIdentityProvider = async n =>
{
if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
{
var result =
await n.OwinContext.Authentication.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationType);
var idToken = result?.Identity.Claims.GetValue("id_token");
if (idToken != null)
{
n.ProtocolMessage.IdTokenHint = idToken;
}
}
await Task.FromResult(0);
}
}
});
My custom attribute inherited from System.Web.Mvc.AuthorizeAttribute:
public class ClaimsAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
//var owinContext = HttpContext.Current.GetOwinContext();
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
{
// 403 we know who you are, but you haven't been granted access
filterContext.Result = new HttpStatusCodeResult(System.Net.HttpStatusCode.Forbidden);
}
else
{
// 401 who are you? go login and then try again
filterContext.Result = new HttpUnauthorizedResult();
}
}
}
where filterContext.HttpContext.User.Identity (also tried HttpContext.Current.User and Thread.CurrentPrincipal) has Claims collection with single 'name' claim from LOCAL AUTHORITY issuer (default one?).
I also modified Web.config to disable forms auth:
<authentication mode="None">
...
<membership>
<providers>
<clear />
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" passwordFormat="Hashed" maxInvalidPasswordAttempts="999" minRequiredPasswordLength="7" minRequiredNonalphanumericCharacters="1" passwordAttemptWindow="3" passwordStrengthRegularExpression="" applicationName="Audit" />
<!--<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" passwordFormat="Hashed" maxInvalidPasswordAttempts="999" minRequiredPasswordLength="7" minRequiredNonalphanumericCharacters="1" passwordAttemptWindow="3" passwordStrengthRegularExpression="" applicationName="Audit" />-->
</providers>
</membership>
<profile>
<providers>
<clear />
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ApplicationServices" applicationName="Audit" />
<!--<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ApplicationServices" applicationName="Audit" />-->
</providers>
</profile>
<roleManager enabled="true">
<roleManager enabled="false">
<providers>
<clear />
<add connectionStringName="ApplicationServices" applicationName="Audit" name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add applicationName="Audit" name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<!--<add connectionStringName="ApplicationServices" applicationName="Audit" name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />-->
<!--<add applicationName="MyApp" name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />-->
</providers>
</roleManager>
...
<handlers>
<remove name="FormsAuthentication" />
<remove name="RoleManager" />
UPDATE 1: I've migrated app from MVC 4 to the latest MVC 5 hoping it is MVC 4 related issue, but, unfortunately, no difference. Apparently, something wrong with my client application/configuration.
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.
I created a simple rest service with routing enabled. The routing is properly working when i run it locally i.e using asp.net development server. But when I deploy the application in IIS (IIS 7.5) then it and try to access the method in the service i get the error HTTP 404.0 Not found. Here is my code :
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class HelloWorldService
{
[WebGet(UriTemplate = "Date")]
public DateTime Date()
{
return System.DateTime.Now;
}
}
Global.asax:
protected void Application_Start(object sender, EventArgs e)
{
RegisterRoutes();
}
private void RegisterRoutes()
{
RouteTable.Routes.Add(new ServiceRoute("ServiceData", new WebServiceHostFactory(), typeof(HelloWorldService)));
}
Web.config:
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</modules>
</system.webServer>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
</configuration>
I also Enabled HTTP Redirection Feature under
Windows Features -> Internet Information Services -> Word Wide Web services -> Common HTTP Features
I also tried Adding handlers like
<handlers>
<add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd" type="System.Web.HttpForbiddenHandler, System.Web,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</handlers>
Also i have tried all the other solutions that were suggested on the web but nothing works. Thanks in advance for any help.
Something is wrong with your RegisterRoutes(). It should be:
private void RegisterRoutes()
{
// Edit the base address of Service1 by replacing the "Service1" string below
RouteTable.Routes.Add(new ServiceRoute("HelloWorldService", new WebServiceHostFactory(), typeof(HelloWorldService)));
}
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.