Entity Framework Core 3 raw SQL missing methods - c#

I'm trying to use EF Core 3 to delete all rows from a table like:
db.MyTable.ExecuteSqlRaw("delete from MyTable;");
But I get the error:
DbSet' does not contain a definition for 'ExecuteSqlRaw' and no accessible extension method 'ExecuteSqlRaw' accepting a first argument of type 'DbSet' could be found (are you missing a using directive or an assembly reference?)
The Microsoft breaking changes page for EF Core 3 does not offer any advice on if there are special packages required to enable this:
https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-3.0/breaking-changes#fromsql-executesql-and-executesqlasync-have-been-renamed
These are the Nuget packages I have installed:
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
<PackageReference Include="System.Linq" Version="4.3.0" />
<PackageReference Include="System.Linq.Expressions" Version="4.3.0" />
<PackageReference Include="System.Linq.Queryable" Version="4.3.0" />
Using statements:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
Note that FromSqlRaw is available, but ExecuteSqlRaw, ExecuteSqlRawAsync , etc are not.
EDIT: I added a using Microsoft.EntityFrameworkCore and the error has changed to:
'DbSet' does not contain a definition for 'ExecuteSqlRaw' and the best extension method overload 'RelationalDatabaseFacadeExtensions.ExecuteSqlRaw(DatabaseFacade, string, params object[])' requires a receiver of type 'DatabaseFacade'

My edit about the new error led me to an answer:
The Microsoft Breaking Changes documentation is just not providing examples for the Execute methods. To get that to work you have to go through the "Database" property instead. So in short, to use those:
Make sure you have using Microsoft.EntityFrameworkCore;
If using an execute use myContext.Database.ExecuteSqlRaw(#"...sql to excxute...")

I had similar issue with dbContext.Database.ExecuteSqlRaw() and it has been fixed by installing package Microsoft.EntityFrameworkCore.SqlServer without even using the package.
try install-package Microsoft.EntityFrameworkCore.SqlServer in your current project.

You need to add NuGet package reference Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions to your project.

Related

Newtonsoft.Json dependency not publishing with the right version on "dotnet publish -o <other folder>"

Problem
So basically, i'm in DLL hell.
I have a dotnet 5.0 + react project where a C# dependency (I assume Microsoft.AspNetCore.Mvc.NewtonsoftJson) needs another one Newtonsoft.Json.
When building and publishing in release or debug in the bin folder, the project runs perfectly fine and all the dependencies and .dll are loaded correctly. But as soon as I use the option -o for dotnet publish, the Newtonsoft.Json.dll created in the published folder is of version 9.0.0.0, which throws an error when trying to run the server in production, since it expects it to be of version 12.x.x.x.
What I've tried
Currently I have a fix, which is to build independently the correct version (12.x.x.x or higher) of the dll file of Newtsoft.Json and put it in the published folder when going in production, but obviously I would like to know of other possible fixes or more direct ones without needing to do extra steps when deploying in production and help people who face the same problem with this dependency or another in the future.
I have tried including the dependency explicitely with the correct version in the .csproj but the dependency still was outputing at version 9.0.0.0.
Another fix would be to downgrade the Microsoft.AspNetCore.Mvc.NewtonsoftJson to a version that accepts 9.0.0.0 but that opens up a whole other can of worms
I have tried clearing my nuget packages, that did not work either.
I have tried this very recent stack overflow solution where the OP faced a similar issue, but their fix of adding False to their test project didn't work for me, since my test project does not use Newtonsoft.Json.
Files
dependencies listed in the .csproj
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.JsonPatch" Version="5.0.11" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="5.0.10" />
<PackageReference Include="Microsoft.AspNetCore.SpaServices.Extensions" Version="5.0.6" />
<PackageReference Include="Microsoft.AspNetCore.ApiAuthorization.IdentityServer" Version="5.0.6" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="5.0.6" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="5.0.6" />
<PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="5.0.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="5.0.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.6" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="Newtonsoft.Json.Bson" Version="1.0.2" />
<PackageReference Include="System.Data.SqlClient" Version="4.8.3" />
</ItemGroup>
Outputed Newtonsoft.Json.dll
// C:\Users\***\published\Newtonsoft.Json.dll
// Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed
// Global type: <Module>
// Architecture: AnyCPU (64-bit preferred)
// Runtime: v4.0.30319
// This assembly is signed with a strong name key.
// Hash algorithm: SHA1
// Public key: 0024000004800000940000000602000000240000525341310004000001000100f561df277c6c0b497d629032b410cdcf286e537c054724f7ffa0164345f62b3e642029d7a80cc351918955328c4adc8a048823ef90b0cf38ea7db0d729caf2b633c3babe08b0310198c1081995c19029bc675193744eab9d7345b8a67258ec17d112cebdbbb2a281487dceeafb9d83aa930f32103fbe1d2911425bc5744002c7
using System;
using System.Diagnostics;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(/*Could not decode attribute arguments.*/)]
[assembly: AssemblyInformationalVersion("9.0.1")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: TargetFramework(".NETStandard,Version=v1.0")]
[assembly: AssemblyTitle("Json.NET .NET Standard 1.0")]
[assembly: InternalsVisibleTo("Newtonsoft.Json.Schema, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f561df277c6c0b497d629032b410cdcf286e537c054724f7ffa0164345f62b3e642029d7a80cc351918955328c4adc8a048823ef90b0cf38ea7db0d729caf2b633c3babe08b0310198c1081995c19029bc675193744eab9d7345b8a67258ec17d112cebdbbb2a281487dceeafb9d83aa930f32103fbe1d2911425bc5744002c7")]
[assembly: InternalsVisibleTo("Newtonsoft.Json.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f561df277c6c0b497d629032b410cdcf286e537c054724f7ffa0164345f62b3e642029d7a80cc351918955328c4adc8a048823ef90b0cf38ea7db0d729caf2b633c3babe08b0310198c1081995c19029bc675193744eab9d7345b8a67258ec17d112cebdbbb2a281487dceeafb9d83aa930f32103fbe1d2911425bc5744002c7")]
[assembly: InternalsVisibleTo("Newtonsoft.Json.Dynamic, PublicKey=0024000004800000940000000602000000240000525341310004000001000100cbd8d53b9d7de30f1f1278f636ec462cf9c254991291e66ebb157a885638a517887633b898ccbcf0d5c5ff7be85a6abe9e765d0ac7cd33c68dac67e7e64530e8222101109f154ab14a941c490ac155cd1d4fcba0fabb49016b4ef28593b015cab5937da31172f03f67d09edda404b88a60023f062ae71d0b2e4438b74cc11dc9")]
[assembly: AssemblyDescription("Json.NET is a popular high-performance JSON framework for .NET")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Newtonsoft")]
[assembly: AssemblyProduct("Json.NET")]
[assembly: AssemblyCopyright("Copyright © James Newton-King 2008")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyFileVersion("9.0.1.19813")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyVersion("9.0.0.0")]
Wish I could give an explanation WHY it happens but I actually don't get it. One clue is to check your project.assets.json in the /obj folder for which dependency actually requires Newtonsoft in the version 9 (do a full-text search on the exact version number).
Then if you have identified the package(s) - in our case it was Microsoft.Extensions.DependencyModel - you can upgrade the package so that it uses a newer Newtonsoft version. In our case we explicitely added this package in the upgraded version. Alternatively, setting "PrivateAssets=true" onto the dependency seems to work too.
If there are some packages with version 9 and some with other packages we actually noticed that the behavior not deterministic, so the published DLL will sometimes be version 9 and sometimes version 13.

How can I use standard 2.0 Entity Framework Library with a NET 5 project?

I have .net framework 4.8 and a NET 5 projects that I both wants to use a netstandard 2.0 library with Entity Framework.
standard 2.0 references, the latest version that works:
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.2.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.2.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.2.6">
NET 5 references:
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.7" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.7">
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.7" />
The NET 5 project references the netstandard 2.0 library
I can then scaffold using just the basic scaffold params
Scaffold-DbContext "Data
Source=SQLSERVER2019.xyz.local;Database=FlexEF;Trusted_Connection=True"
Microsoft.EntityFrameworkCore.SqlServer
But my context class is then full of errors like:
Error CS1660 Cannot convert lambda expression to type 'string' because it is not a delegate type
Error CS1061 'EntityTypeBuilder' does not contain a definition for 'HasNoKey' and no accessible extension method 'HasNoKey' accepting a first argument of type 'EntityTypeBuilder' could be found (are you missing a using directive or an assembly reference?)
Error CS1061 'PropertyBuilder<short?>' does not contain a definition for 'HasComment' and no accessible extension method 'HasComment' accepting a first argument of type 'PropertyBuilder<short?>' could be found (are you missing a using directive or an assembly reference?)
What have I misunderstood?
So it turns out that in my context I only need to have this one using
using Microsoft.EntityFrameworkCore;
In NET5 I only need to reference the 3 packages, in Standard2.0 I need to add a lot more packages, that apparently belongs to the same namespace.
Such as:
Microsoft.EntityFrameworkCore.Abstractions
Microsoft.EntityFrameworkCore.Design
etc etc.
Sigh...

Using MongoDB.Driver inside azure functions

I'm trying to use an azure function to upload data to a mongodb but I get an error saying "The type or namespace name 'MongoDB' could not be found (are you missing a using directive or an assembly reference?)". I have a function.proj file that has refs to the MongoDB.Driver package but that doesn't seem to be working. I tried using the #r sytax to import the package but thats not working either. I'm using version 3 of the azure funtion runtime. Can anybody point me in the right direction?
Contents of the function.proj file
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="MongoDB.Driver.Core" Version="2.11.3" />
<PackageReference Include="MongoDB.Driver" Version="2.11.3" />
<PackageReference Include="MongoDB.Bson" Version="2.11.3" />
<_FunctionsSkipCleanOutput>true</_FunctionsSkipCleanOutput>
</ItemGroup>
Using directives
#r "Newtonsoft.Json"
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using MongoDB.Driver;
using MongoDB.Bson;
Update:
Thanks for Ggd Hhdhd's working. Azure function can not install some package on azure when based on crx. The solution is to send related dll directly to the bin directory on azure. This is the doc:
https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-csharp#referencing-custom-assemblies
And this is the structure:
https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-csharp#folder-structure
Original Answer:
Please don't use C# script to do this.
Some package is not supported to install in C# script azure function on azure. I notice you install three package, but in fact, you just need to install MongoDB.Driver is ok. MongoDB.Driver is an integrated package that includes MongoDB.Driver.Core and MongoDB.Bson.
Problem is not from your code. The problem comes from just install the MongoDB.Driver package will broken the function.
By the way, the format of the function.proj should be like this:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="MongoDB.Driver" Version="2.11.3" />
</ItemGroup>
</Project>
You miss the </Project>.
I try to find some package but didn't find.

Compilation fo index.cshtml throws an runtime error

I am trying to update a private nuget package and some changes for that has lead to me an error screen of this.
The error essentially is
An error occurred during the compilation of a resource required to process this request. Please review the following specific error details and modify your source code appropriately.
Generated Code
One or more compilation references may be missing. If you're seeing this in a published application, set 'CopyRefAssembliesToPublishDirectory' to true in your project file to ensure files in the refs directory are published.The type or namespace name 'Hosting' does not exist in the namespace 'Microsoft.AspNetCore.Razor' (are you missing an assembly reference?)+[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Home_Index), #"mvc.1.0.view", #"/Views/Home/Index.cshtml")]
The type or namespace name 'Hosting' does not exist in the namespace 'Microsoft.AspNetCore.Razor' (are you missing an assembly reference?)
I have done my homework by trying various solutions over the net such as
1) setting the CopyRefAssembliesToPublishDirectory' to true in .csproj file.
2) Remove ASP.Net Temporary files
still no luck.
so far i understand that i tried opening a web page and when asp.net tried to compile on the fly as it does it couldn't build the solution.
Is my understanding complete and what else can i do to debug and reach the solution?
Here are some .csproj lines
<TargetFramework>net461</TargetFramework>
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.3" />
<PackageReference Include="System.Net.Http" Version="4.3.3" />
Being the private nature i cant share much of the code but only common things.
any help is much appreciated.
Setting it to <Project Sdk="Microsoft.NET.Sdk.Web" ToolsVersion="15.0"> and including the following files
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.ViewCompilation" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.SpaServices" Version="2.2.0" /> Helped resolving the issue

How to reference assemblies using Visual Studio Code?

I would like to reference the System.Drawing.dll in a console app I am writing using Visual Studio Code on OSX. i.e. I want to use these using statements
using System.Drawing;
using System.Drawing.Imaging;
to avoid this build error
Program.cs(56,20): error CS0246: The type or namespace name `Bitmap' could not be found. Are you missing an assembly reference?
I can't find a tutorial on this, I don't even know if the dll is available in .net core or mono or whatever visual-studio-code uses.
In your .csproj file, add your dependency as a PackageReference in an ItemGroup, then run dotnet restore or nuget restore. Example:
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Xml" />
<Reference Include="System.Core" />
<Reference Include="Xamarin.iOS" />
<PackageReference Include="Realm" Version="2.1.0" />
<PackageReference Include="xunit">
<Version>2.3.1</Version>
</PackageReference>
</ItemGroup>
Take a look at this article for a full explanation.
The new .NET Core SDK restore command is dotnet restore
To add any asssembly reference in Visual Studio Code, please refer to my post.
Mono offers a WinForms pipeline implementation that you can leverage, that includes support for System.Drawing.

Categories

Resources