The model backing my context has changed - c#-4.0

I have a class library project where my POCO classes live along with a Dbcontext. I am using Code First with data migrations and everything has gone great up to this point. I use the class library in a console application test project and it still works fine there, but I am also trying to use the same exact class library in an MVC project and I get a "The model backing the context has changed since the database was created". Whenever I make a change to the model, I do the database migration update and everything goes well. The model has not still works in the console application just fine.
I have this method in a controller where I am trying to access the context:
public MultiSelectList GetListOfPossibleDispositions()
{
List<DALDevices3.Dispositions> dispositions = new List<Dispositions>();
dispositions = context.Dispositions.GroupBy(d=>d.Description).Select(grp=>grp.First()).ToList();
dispositions.OrderBy(d=>d.Description);
selectListDispositions = new MultiSelectList(dispositions, "id", "Description");
context.Dispose();
return selectListDispositions;
}
Any thought on what might be causing this issue or a possible work around ?
Thanks

In my MVC application I had a connection string name like this:
<add name="DALDevices3.DeviceContextConnectionString" connectionString="Data Source=....
so I removed the connection string since it is code first and still received the same error. I put the connection string back like this:
<add name="DALDevices3.DeviceContext" connectionString="Data Source=....
and the application works. So a connection string is not required in the DAL application, but is needed in the consuming application.

Related

Blazor Component (in library) and JSInterop

I've created a Blazor Component within a full Blazor project and all works well.
However, when I move this component to it's own Razor Class Library project, I am now getting an error that I cannot use JSInterop until a connection with the server is made. I am running my code in the OnAfterRenderAsync() method.
I had to alter the code a little when I made the change.
In a full Blazor project, JSInterop is provided for you with DI in the Startup class. But this is not the case with a calss library.
So instead of "#inject JSInterop js" in the page, I had to set it up like this -
private IJSRuntime js { get; set; }
protected override void OnInitialized()
{
js = ScopedServices.GetRequiredService<IJSRuntime>();
}
From the sketchy details available on the web, I'm assuming this gets the service from the Parent project.
Using debugging, I can see that js is NOT null. It does seem to have been set to a valid object.
Can anyone point me in the right direction?
The server pre-renders, so your code will run before there is a client connection to the server. When rendering in OnAfterRenderAsync you should only use IJSRuntime when the firstRender parameter is true, or any point after that, but never before.
Found the solution to my problem and it has rendered my initial question irrelevant.
When I copied my component to it's own class library project, it would not compile. It gave me an error on the line #inject JSInterop js.
This led me to believe that it didn't know how to inject this as it is not set during the Startup of the project, as it is in a Blazor app.
So I cobbled together the code to get a reference via ScopedServices.GetRequiredService().
This did create an object but did not have _clientProxy set which contains the connection to the server.
So digging round I managed to find a complete component library example project at BlazorHelp Website
This did have the JSInterop injected in the Blazor file. So I reverted my code back to the original code that worked in the full project and tried to compile. It gave me the same error. So I deleted the #inject JSInterop js line and typed it in again.
IT RECOGNIZED IT!!!
It still failed to compile, not recognizing a custom type (Pivot) and asking whether I had included a reference to it.
[CascadingParameter] public Pivot OwnerPivot { get; set; }
I deleted the word Pivot and retyped it and, voila, it compiled.
So it looks like there some sort of error in VS2019 or the razor compiler, where deleting code in the source file and re-entering caused it to recognize and compile.

Does MvcSiteMapProvider support "Sql Server" session state?

I am trying to use the MvcSiteMapProvider in an application that is configured with SqlServer session state mode.
However, I get an exception the moment I call the RegisterRoutes method of XmlSiteMapController class, like this:
public static void RegisterRoutes(RouteCollection routes)
{
// ...
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
// Add our route registration for MvcSiteMapProvider sitemaps
MvcSiteMapProvider.Web.Mvc.XmlSiteMapController.RegisterRoutes(routes);
}
Then I get an exception saying
Type 'System.Web.Routing.RouteValueDictionary' in Assembly 'System.Web, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a' is not marked as serializable.
This makes me think MvcSiteMapProvider does not support SqlServer session state mode. Does it?
Thanks!
Unless you have customized it, MvcSiteMapProvider does not interact with session state in any way. So, it should work with any mode of session state (I haven't tested it with SqlServer mode, so if you continue having issues I suggest you open a new issue about it). Please see How to Make MvcSiteMapProvider Remember a User's Position for an explanation about how it works without session state.
The error posted indicates your application is trying to serialize the System.Web.Routing.RouteValueDictionary, which is not something that MvcSiteMapProvider does.
On a side note, you don't need to call XmlSiteMapController.RegisterRoutes explicitly from an MVC 4 application as long as you have installed the MvcSiteMapProvider.MVC4 NuGet package. This method is called automatically using WebActivator. It is possible you might be having issues by calling it twice.
MvcSiteMapProvider would need to interact with state servers if you want to put a node into session state for any reason. I do that to keep track of objects that I have associated with the nodes, since MvcSiteMapProvider forgets any state information upon each new request.
If you download the code you can add the project to your solution.
If you do a replace and
Replace public class with [System.Serializable]\r\n\public class
Also replace public abstract class with [System.Serializable]\r\n\public abstract class
The remove the attribute off the JavaScriptSerializerAdapter class.
then it will be usable with State Servers.

How to configure entity framwork (Model First ) on microsoft azure?

I was using EntityFramwok (code First) in my application, but for some cause i have to change entityframwork approch to Database First. i have configured the project on local successfully, when published the code to microsoft azure server and tried to login in my application it throws an exception: " The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development. This will not work correctly. To fix this problem do not remove the line of code that throws this exception. If you wish to use Database First or Model First, then make sure that the Entity Framework connection string is included in the app.config or web.config of the start-up project. If you are creating your own DbConnection, then make sure that it is an EntityConnection and not some other type of DbConnection, and that you pass it to one of the base DbContext constructors that take a DbConnection. To learn more about Code First, Database First, and Model First see the Entity Framework documentation here: http://go.microsoft.com/fwlink/?LinkId=394715 "
I have searched about it on google but can't found any clue, seems i am the only person who got this exception :( does anybody knows about this. I am new to azure so don't know how to change the entityframwork approach there. any help or suggestions will be appreciated :)
I just deployed a database first project to Azure and ran into the identical error. Seems like there is a lot more information when googling now than there was when you asked this question. Regardless, none of it was entirely on point for me though and I had to experiment to come up with the solution.
Here's my scenario:
My database first DB is hosted on Azure as well and the connection string that Azure recommends for ADO.NET is what I put in my Web.Release.config transformation entries. I have two connection strings, one is the default connection and the other is the one that is used for the db first project. The solution was to use the same (functioning) content from the Web.config connection string and only replace the inner portion with Azure db connection string. I was cut & past happy at first and just wiped out the full content of the connection string leading to the error.
Lot's of the info within the connection string is particular to your project and the db first entities you have created in the project. Here are a couple examples from what I have:
You're Web.config should have connection strings for you local dev environment (chances are these were created for you by the DB first wizard):
<configuration>
...
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-WebRole1-20150218073037.mdf;Initial Catalog=aspnet-WebRole1-20150218073037;Integrated Security=True" providerName="System.Data.SqlClient" />
<add name="DbFirstModelEntities" connectionString="metadata=res://*/Models.DbFirstModel.csdl|res://*/Models.DbFirstModel.ssdl|res://*/Models.DbFirstModel.msl;provider=System.Data.SqlClient;provider connection string="data source=(localdb)\ProjectsV12;initial catalog=DbFirstData;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
...
</configuration>
Notice how the dbfirst connection string starts out with a bunch of meta data about the db models. This stuff is important!!
Next comes the correct Web.Release.config connection string transformation (just posting the DB first one, but you'd need to do something similar for any others that you have):
<connectionStrings>
<add name="DbFirstModelEntities"
connectionString="metadata=res://*/Models.DbFirstModel.csdl|res://*/Models.DbFirstModel.ssdl|res://*/Models.DbFirstModel.msl;provider=System.Data.SqlClient;provider connection string="Server=tcp:<yourdatabesserver>.database.windows.net,1433;Database=DbFirstData;User ID=<user>;Password=<password>;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;MultipleActiveResultSets=True;App=EntityFramework""
providerName="System.Data.EntityClient"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>
So long story, if you're encountering this error after publishing to azure: go check your transformations and make sure you're not removing all that important meta data!
While configuring your website and database on the azure server you have to define a connection string and the name of the connection string should not be the same as connection string name in your web.config file. I just did rename the connection string name in my web.config and problem solved. :)

entity Framework 5 changing providers at runtime

I have an application that runs at several client sites. I have to support different DBMS at the locations (SQL Server, DB2, Oracle). I am converting the application from VC++ 6.0 with an ODBC based data layer to Visual Studio 2012 and would like to use Entity Framework (database first). I am having troubles changing the database provider at runtime in my sample application. I changed the connect string in the app.config from a SQL Server to DB2 connect string and changed the default connection factory. Now when I run the program I can connect to the database (at least there is no error) but when I iterate over the linq results I get the exception:
Unable to cast object of type 'IBM.Data.DB2.DB2Connection' to type 'System.Data.SqlClient.SqlConnection'
Here is the program code:
private void btnList_Click(object sender, EventArgs e)
{
using (var ListBill = new LB402_TestEntities())
{
var queryGroups = from Groups in ListBill.LB_Group
select Groups.GroupName;
foreach (string name in queryGroups)
{
lbGroups.Items.Add(name);
}
}
}
The modifed portions of the app.config are:
<defaultConnectionFactory type="IBM.Data.DB2.Entity.DB2ConnectionFactory, EntityFramework" />
<add name="LB402_TestEntities" connectionString="metadata=res://*/LB402.csdl|res://*/LB402.ssdl|res://*/LB402.msl;provider=IBM.Data.DB2;provider connection string="Server=db210:50000;Database=LISTBILL;uid=uuuuu;pwd=ppppp;"" providerName="System.Data.EntityClient" />
From my searching and reading it seems like I should be able to do this, but I am obviously missing something.
Changing connection string is not enough. EDMX file consist of three part and one is provider specific (that is the .ssdl reference from connection string). You need to have this part for every database you need to support and you need to have EF provider for every such database. The problem is that EDMX designer does not support modelling for multiple providers. So you must either have separate EDMX for every database = huge duplicity or you must start maintaining SSDL files for other databases manually (it is XML).
You should make some small Proof-of-concept with code first mapping and DbContext API because it doesn't have these obstacles - SSDL is generated at runtime from code mapping and provider specified in connection string.

Subsonic 3 Class Library & Winforms App Null IDataProvider BUG

I have got a class library project and a winforms app.
Everything is getting geerated fine and my Winforms app references the class library but as soon as I run it and try to retreive data it comes up with dataprovider is null.
The one thing to note is that I do not have a app.config in my Winforms app only in the class library. Do I need one in the Winforms app and if so what do I put in it?
Thanks
UPDATE: I think I have found a bug in Query\Select.cs
public Select(IDataProvider provider, params string[] columns)
{
//_provider is null
//provider is populated correctly
this.sqlFragment = new SqlFragment(_provider);
_provider = provider;
SelectColumnList = columns;
SQLCommand = this.sqlFragment.SELECT;
}
Yes, you need an App.config in your Winforms app and you put your connection string there. It's worth noting that an App.config is pointless in a class library EXCEPT when you're using SubSonic :), which will pull one from the project.
Class libraries don't have their own configuration - they pull their config from the execution environment.

Resources