Covering Indexes in NPGSQL ,.Net Core - npgsql

I am trying to include non-key column in my index using NPGSQL, .NET Core.
I have followed the example found here https://www.npgsql.org/efcore/modeling/indexes.html
protected override void OnConfiguring(DbContextOptionsBuilder builder)
=> modelBuilder.Entity<Device>()
.ForNpgsqlHasIndex(b => b.Id)
.ForNpgsqlInclude(b => b.Name);
The example refers to "modelBuilder" but what is modelBuilder please (as it does not exist in the current context)?
I changed it to refer to the builder variable but it did not work as DbContextOptionsBuilder does not contain a definition for 'Entity' and no 'Entity' accepting argument 'Device' (Device exists).
I then changed it to refer to ModelBuilder type variable, it also did not work (No override of OnConfiguring(ModelBuilder ...)
Any suggestions please?
Thanks!

Which version of EF Core provider for PostgreSQL do you use?
Check the entry in your *.csproj file.
It should be the 2.2.0 version as this feature is introduced in the 2.2.0.
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="2.2.0" />
Hovever it seems that the docs have some mistake. Try to configure the indexes in the
protected override void OnModelCreating(ModelBuilder modelBuilder)
If I manage to verify the results on my own I will let you know.
If the methods are still not visible and calling them inside the OnModelCreating() does not help try to force restoring Nuget packages.
If you use Rider you can do it via Tools -> NuGet -> NuGet Force Restore
EDIT: Check also if your PostgreSQL version is 11 (or higher)

Related

'AuthenticationBuilder' does not contain a definition for 'AddMicrosoftIdentityWebApp'

I'm attempting to add support for Graph into a .Net 6 application. I've previously used Graph in a .Net 5 application but I'm having some trouble understanding how to wire things up using the .Net 6 "simplified" startup.
I've included both:
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;
in the header of Program.cs but I'm getting an error with AddMicrosoftIdentityWebApp in the following:
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
.EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
.AddMicrosoftGraph(builder.Configuration.GetSection("DownstreamApi"))
.AddInMemoryTokenCaches();
The error I'm getting is:
Error CS1061 'AuthenticationBuilder' does not contain a definition for 'AddMicrosoftIdentityWebApp' and no accessible extension method 'AddMicrosoftIdentityWebApp' accepting a first argument of type 'AuthenticationBuilder' could be found (are you missing a using directive or an assembly reference?)
I'm fairly sure that I'm overlooking something pretty simple, but I cannot find it.
Any suggestions are much appreciated.
Thanks for the response.
As it turns out, I found that the problem was with an incorrect package being installed. I had included Decos.Microsoft.Indentity.Web in the packages for the solution. I suspect that there were some collisions occurring here. Once I removed the package the error no longer manifests itself.
"Error CS1061 'AuthenticationBuilder' does not contain a definition for 'AddMicrosoftIdentityWebApp' and no accessible extension method 'AddMicrosoftIdentityWebApp' accepting a first argument of type 'AuthenticationBuilder' could be found (are you missing a using directive or an assembly reference?)"
To resolve the above error, please try the below suggestions if helpful:
When you are including Microsoft.Identity.Web, Microsoft.Identity.Web.UI packages, these libraries are used to simplify the process of signing-in a user and acquiring tokens for Microsoft Graph.
Try modifying your configured services method by removing the prefix builder like below:
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))
.EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
.AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))
.AddInMemoryTokenCaches();
To sign-in a user for your application with Microsoft identity platform endpoint AddMicrosoftIdentityWebApp() is used.
EnableTokenAcquisitionToCallDownstreamApi() and AddMicrosoftGraph adds support to call Microsoft Graph.
Otherwise, If you want to use builder, make sure to add the package using Microsoft.AspNetCore.Identity and define the builder as below:
var builder = WebApplication.CreateBuilder(args);
For more in detail, please refer below links:
active-directory-aspnetcore-webapp-openidconnect-v2/README.md at master · Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2 · GitHub.
Configure ASP.NET Core Identity | Microsoft Docs.

MicrosoftEntityFrameworkCore is unable find migrations from the assembly

I am using entity framework core Ver. 2.2.4, and I am maintaining a separate assembly for maintaining ef generated migrations. During the application startup, when I try to perform context.Database.Migrate(), I am getting the following message in the output log
No migrations were found in assembly 'MyProject.Core'.
I have included optionsBuilder.UseSqlite(GetConnectionString(), builder => builder.MigrationsAssembly("MyProject.Core")); to load the appropriate assembly to find the migrations, but no luck. Any Idea what's going on?
After looking into the EF Core source code, I figured out what the issue was. The problem was with my application db context class i.e. AppDbContext:DbContext. I had this class in my core project marked as abstract and later I was deriving from the class in the android project to define connection string. Looks like EF Core will ignore all the migrations marked with [DbContext(typeof(AppDbContext))] attribute containing abstract db context types. Once I made my db context class concrete, my migrations started working.
Reference your migrations assembly from your project.
If you can't because it causes a circular dependency, set the output path of your migrations assembly to your main project's directory: (or otherwise copy it there)
<PropertyGroup>
<BaseOutputPath>..\MyStartupProject\bin\</BaseOutputPath>
</PropertyGroup>

No connection string named 'MyApplicationEntities' could be found in the application config file

I just install EF 4.3 and trying to upgrade my project with migration. however I am getting issues with trying to execute add-migration initial to my project via Package Manager console.
It is throwing any exception now No connection string named 'MyApplicationEntities' could be found in the application config file.
Now my config has it all
<connectionStrings>
<add name="MyApplicationEntities"
connectionString="metadata=res://*/DataModel.csdl|res://*/DataModel.ssdl|res://*/DataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=localhost;initial catalog=MyApplicationEntitiesDB;integrated security=True;multipleactiveresultsets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
I am not sure what is the issue is it a bug in EF 4.3 or there is something I am not doing right.
I thought this post has solved the issue but not quite.
Anyone got an answer.
Appreciate Sanj.
Ah, figured this out accidentally.
I had to remove
public MasterEntities()
: base("name=MyApplicationEntities")
// ^^^^^
{
}
to
public MasterEntities()
: base("MyApplicationEntities")
{
}
EF 4.3 does not like connection string being called name=xxxxx
The solution as Sanj pointed out is that you need to copy the connection string from your database project's App.config to the web project's web.config. I'm not sure why the above answer is marked as correct. I'm adding this as an answer instead of a comment so future readers will spot this.
I had the same error but I already had a web.config file with the correct connection string name and a DbContext declared correctly. However, I noticed when I ran add-migration with -Verbose it state the 'Startup Project' as a different project than the one containing my context. So I change the Startup Project, re-ran the add-migration and it all worked!!
Make sure your statup project config file has the connection string.This link may help you.
I also had this problem and solved it by
Selecting the correct StartUp project.
Rerunning the command on Package Manager Console.
Things worked out as expected.
I also encountered the similar exception. AppConfig is originally gets created in the project that we generate the entity model.
But if you are executing the application using some other project (there are several Projects in my solution), the AppConfig needs to be included in the project which is being executed.
1. ctor => Context
public MasterEntities()
: base("ConnectionStringName")
{
}
2. config file
<add name="ConnectionStringName"
connectionString="Data Source=.;Initial Catalog=DatabaseName;User Id=sa; Password=YourPass;"
providerName ="System.Data.SqlClient" />
3. in Sulation Exporer right click the project and select 'Set as
startup project'
4. in PackageManagerConsole Change Default Project to Your Project of
context class.
5. then:
add-migration new
or added ConnectionString to config file of working Project.
In my case, i got two projects:
I just have to copy the connection string from DAL App.Config project to WPF App.Config project
If you get this error and you're working with Oracle DBs in .NET, check your existing <connectionStrings> tag in the startup project (web.config in web projects, app.config in console/Windows projects), and make sure Oracle didn't replace it with nonsense.
Installing the Oracle.ManagedDataAccess.* assemblies from NuGet does this obnoxious thing where it deletes whatever <connectionStrings> tag that already existed in destination project and replaces it with a new one at the bottom containing a boilerplate Oracle connection string.
Do a git diff or whatever you use to diff changes and focus on your *.config files. Restore old connection strings as needed, then rebuild and try again.
For all others, just remember that the <connectionStrings> tag is only read from the startup project's configuration (aka the entry assembly). If you have your DB stuff in another project that is referenced by your startup project, and you have an app.config in that DB project with a <connectionStrings> tag in it, that tag is only used for for scaffolding EF stuff. After that, the DB project reads the tag from the startup project's configuration instead of its own.
For anyone arriving here because they are getting this error while working with WPF in Visual Studio, please take a look at this post:
Does MVVM stop the ability for the Visual Studio Designer to show xaml?

How/Where I do to override the app.config ConnectionString at runtime?

I'm using Entity Framework 4.1 Code First, Sqlite and WPF.
I want to redefine the app.config ConnectionString to sqlite, so I can define the Data Source (path for Sqlite database file) at runtime.
My guess is using the EntityConnectionStringBuilder to create the connection string. But I don't know what the event where I build and assign the connection string so the EF Code First will detect the change and will use the newer ConnectionString in all the code for the application (instead to use the app.config ConnectionString). I imagine that it's to be placed on Application_Startup event, but I don't know if this is the best pratice.
Thank you in advance.
If that's what you're after,
You can pass the string at runtime via DbContext(string) constructor - see here for more DbContext(string)
You could also make your context implementation take that param and pass it to the base DbContext.
hope this helps
IF you are using EF 4.1 CF, then once you do your *.edmx file generation it should create your app.config automatically. You don't need to create your own app.config or change it if you have an existing one.

What does this WCF error mean: "Custom tool warning: Cannot import wsdl:portType"

I created a WCF service library project in my solution, and have service references to this. I use the services from a class library, so I have references from my WPF application project in addition to the class library. Services are set up straight forward - only changed to get async service functions.
Everything was working fine - until I wanted to update my service references. It failed, so I eventually rolled back and retried, but it failed even then! So - updating the service references fails without doing any changes to it. Why?!
The error I get is this one:
Custom tool error: Failed to generate code for the service reference
'MyServiceReference'. Please check other error and warning messages for details.
The warning gives more information:
Custom tool warning: Cannot import wsdl:portType
Detail: An exception was thrown while running a WSDL import extension:
System.ServiceModel.Description.DataContractSerializerMessageContractImporter
Error: List of referenced types contains more than one type with data contract name 'Patient' in
namespace 'http://schemas.datacontract.org/2004/07/MyApp.Model'. Need to exclude all but one of the
following types. Only matching types can be valid references:
"MyApp.Dashboard.MyServiceReference.Patient, Medski.Dashboard, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" (matching)
"MyApp.Model.Patient, MyApp.Model, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" (matching)
XPath to Error Source: //wsdl:definitions[#targetNamespace='http://tempuri.org/']/wsdl:portType[#name='ISomeService']
There are two similar warnings too saying:
Custom tool warning: Cannot import wsdl:binding
Detail: There was an error importing a wsdl:portType that the wsdl:binding is dependent on.
XPath to wsdl:portType: //wsdl:definitions[#targetNamespace='http://tempuri.org/']/wsdl:portType[#name='ISomeService']
XPath to Error Source: //wsdl:definitions[#targetNamespace='http://tempuri.org/']/wsdl:binding[#name='WSHttpBinding_ISomeService']
And the same for:
Custom tool warning: Cannot import wsdl:port ..
I find this all confusing.. I don't have a Patient class on the client side Dashboard except the one I got through the service reference. So what does it mean? And why does it suddenly show? Remember: I didn't even change anything!
Now, the solution to this was found here, but without an explanation to what this means. So; in the "Configure service reference" for the service I uncheck the "Reuse types in the referenced assemblies" checkbox. Rebuilding now it all works fine without problems. But what did I really change? Will this make an impact on my application? And when should one uncheck this? I do want to reuse the types I've set up DataContract on, but no more. Will I still get access to those without this checked?
I found my answer here: http://www.lukepuplett.com/2010/07/note-to-self-don-let-wcf-svcutil-reuse.html
Long story short: I unchecked Reuse types in reference assemblies from the Advanced menu.
I don't know if this matters but i'm not using MVC, but Web Forms.
When you add a service reference, there are two ways the types that are used by the service can be handled:
The types are stored in a dll, and that dll is referenced from both the client and the server application.
The types are not in a dll referenced by the client. In that case the tool that creates the service reference, will create the types in the references.cs file.
There are many things that can go wrong. We have found that if the tool crashes, it is sometimes faster to delete the service reference and start again.
We have stopped using service reference. For projects where we have control of the client and the service, we use the method described in this screencast.
I also had this issue Today. It took me one entire day to find my mistake. Hope it helps.
My class that weren't able to be imported has a cutom enum type property. This property is marked as DataMember and the Enum is also marked as DataContract. Everything fine so far.
I just forgot to mark every enum member as EnumMember.
So i changed
[DataContract]
public enum SortMethodType
{
Default = 0,
Popularity = 1,
ReleaseDate = 2,
PublishedDate = 3,
TranslatedTitle = 4,
OriginalTitle = 5,
UserRating = 6,
Duration = 7
}
To this:
[DataContract]
public enum SortMethodType
{
[EnumMember]
Default = 0,
[EnumMember]
Popularity = 1,
[EnumMember]
ReleaseDate = 2,
[EnumMember]
PublishedDate = 3,
[EnumMember]
TranslatedTitle = 4,
[EnumMember]
OriginalTitle = 5,
[EnumMember]
UserRating = 6,
[EnumMember]
Duration = 7
}
And it finally worked!
Go to Advanced properties while adding reference and remove "System.Window.Browser" from the checklist, It solves the problem.
that might sound weird, but I got it fixed by deleting the references, then closing Visual Studio, and reopening it again, and finally adding the references again.
I think the custom tool thing needed to be restarted or something.
I constantly run across this error while it works on another developers machine. Even though I'm a full admin everywhere in my virtual machine, I tried closing Visual Studio, and re-opening with 'Run As Administrator' and it magically worked.
Good luck.
I got the warning after upgrading my solution from Visual Studio (VS) 2010 to 2013 and changing each project's .NET Framework from 4 to 4.5.1. I closed VS and re-opened and the warnings went away.
One downside of turning off 'reuse types in referenced assemblies' is that it can cause issues with ambiguous references. This is due to the service reference creating those objects again in the reference .cs file, and your code implementing the service may be referencing them from the original namespace.
When this scenario occurs I find it useful to check the 'reuse types in specified referenced assemblies' which allows me to choose the ones with ambiguous references only, which resolves the issue quickly that way.
Hope it helps someone else.
My interfaces of the WCF service are in an assembly, the implementation is in an another and the service reference is in yet another assembly, separate from the clients of the service reference. I got the error message right after I applied the DataContract to an enum. After I applied EnumMember to the fields of the enum, the issue resolved.
If in doubt that your service doesn't have any problems (such as problems with enums, or non-serializable classes as mentioned by others) then try to create a new project with a new reference.
I am using Silverlight 5 and I had tried to delete and recreate the reference several times. The reference.cs file just came up completely empty each time and it had been literally years since I'd created it so trying to figure out what had changed in the service was out of the question.
I noticed that the error contained references to 2.0.5.0. Now I don't even know if this is actually relevant to the Silverlight version, but it made me think of just creating a brand new project and then suddenly everything worked.
Warning 2 Custom tool warning: Cannot import wsdl:portType Detail: An
exception was thrown while running a WSDL import extension:
System.ServiceModel.Description.DataContractSerializerMessageContractImporter
Error: Could not load file or assembly 'System.Xml, Version=2.0.5.0,
Culture=neutral, PublicKeyToken=7cec85d7bea7798e' or one of its
dependencies. The system cannot find the file specified. XPath to
Error Source: //wsdl:definitions[#targetNamespace='']/wsdl:port
Type[#name='IShoppingCart']
I was looking over my project and I was having this same issue. It turned out to be different versions of the same DLL on the WCF vs. Web Site.
Web site had a newer version of the DLL and the service was referencing an older version of the DLL. Once they were all in sync all worked well.
I experienced the same error. I struggled for almost a day trying to find out what was going wrong. The clue for me were the warnings that VS was throwing. It was trying to do some kind of mapping to Yahoo.Yui.Compressor.dll, a library I had added and removed (because I decided not to use it) a couple of days before. It was shocking because the library wasn't there, but somehow it was trying to reference it.
Finally, I restore this dll from the Trash, and then I could update my service reference successfully.
For anyone here in the future, I had the same error but caused by version issues, in two different ways.
I have two WCF services and two client applications that talk via the service references. I updated a nuget package on both sides and tried to update the service reference and got this error.
Deleting didn't help. Unchecking "reuse assemblies" is not desired as I need to reuse them - that's the whole point.
In the end, there were two separate issues:
1) The first issue, I believe, was a visual studio caching issue. I meticulously went over all of the references and found no issues but it still reported being unable to find the previous version of the file. I uninstalled all of the nuget packages, restarted visual studio, and reinstalled them. Updating the service reference worked.
2) The second issue was caused by a dependency issue. I updated the nuget package on both sides and everything appeared correct, but an unmarked dependency was out of sync. Example:
Package Foo v1 references Bar v1.
It is possible to update Foo and Bar to v2 independently without updating the reference.
If you install both Foo and Bar v2 the service reference tool will scan Foo v2, see the reference to Bar v1, and fail because it can't find the older version.
This is only reported correctly if you update the version numbers of your dll for every package.
Visual Studio and MSBuild will have no problem building the application but the service reference will have a terrible time trying to resolve everything.
I hope this helps someone.

Resources