I am developing simple API project using .NET Core 6. This is the application structure.
Project Solution
StudentAPI (Main project - .NET Core Web API)
StudentAPI.DataAccess (Data Access Layer - created .NET class library)
StudentAPI.Models (This class library contains models ex: student/grade/address/course)
This is my Data Context Class (StudentAPI.DataAccess)
public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> options) : base(options)
{
}
public DbSet<Student> Students { get; set; }
public DbSet<Course> Courses { get; set; }
public DbSet<Address> Addresses { get; set; }
public DbSet<Grade> Grades { get; set; }
}
This is my Program.cs class (Main project - .NET Core Web API)
using Microsoft.EntityFrameworkCore;
using StudentAPI.DataAccess.Data;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<DataContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
This is the appsetting.JSON file (Main project - .NET Core Web API)
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Server=.; Database=dotnet-rpg-test; Trusted_Connection=true;"
}
}
I tried to add initial migration using below command
dotnet ef migrations add 'Initial' --project .\StudentAPI.DataAccess
But I got below error message when I tried to add migration.
Unable to create an object of type 'DataContext'. For the different patterns supported
at design time, see https://go.microsoft.com/fwlink/?linkid=851728
Here I have selected StudentAPI (Main project - .NET Core Web API) as StartUp project and in package manager console selected StudentAPI.DataAccess as default project.
Kindly someone can tell me the why I am getting this error. I just want to divide my project into separate layers. And please tell me how to resolve this issue.Thanks.
I'm trying to upgrade my .Net core 2.2 application to .net 5.0
This line no longer works:
services.AddIdentity<ApplicationUser, IdentityRole>
.AddEntityFrameworkStores<DataContext>()
.AddDefaultTokenProviders();
I get the message:
'IdentityBuilder' does not contain a definition for
'AddEntityFrameworkStores' and no accessible extension method
'AddEntityFrameworkStores' accepting a first argument of type
'IdentityBuilder' could be found
So based on my research I tried:
services.AddIdentity<ApplicationUser, IdentityRole>
.AddUserStore<DataContext>()
.AddDefaultTokenProviders();
However, while this compiles I get the following error at runtime:
Implementation type 'motorsport.Models.DataContext' can't be converted
to service type 'Microsoft.AspNetCore.Identity.IUserStore`
This is my DataContext:
public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> options) : base(options)
{ }
public virtual DbSet<ApplicationUser> ApplicationUsers { get; set; }
public virtual DbSet<RefreshToken> RefreshTokens { get; set; }
}
What am I doing wrong? Note that my application is API only, I'm not using Razor Views at all.
You need to install Microsoft.AspNetCore.Identity.EntityFrameworkCore which provides types for persisting Identity data with Entity Framework Core.
Because AddEntityFrameworkStores has been moved into separate NuGet package Microsoft.AspNetCore.Identity.EntityFrameworkCore.
I’ve an issue when using a .Net Standard 2.0 Nuget (same issue linking directly project) in WASM (#uno-platform):
Deserialization requires à parameterless constructor (Microsoft & Newtonsoft deserializator).
Obviously, the involved classes have parameterless constructors and the Nuget is working fine with UWP, WPF and Xamarin projects:
public class MCEFile
{
public List<Form> Forms { get; set; }
public List<Item> Items { get; set; }
[JsonConstructor]
public MCEFile()
{
Forms = new List<Form>();
Items = new List<Item>();
}
}
public class Item
{
public long ID { get; set; }
...
// - - - - - -
[JsonConstructor]
public Item()
{
// dummy for WASM
}
}
Any clue? Is there a solution or workaround? Or an issue I can follow?
Regards,
Michael
This is generally caused by a linker configuration issue.
If the class you are deserializing is located in an assembly or project that is not directly in the WebAssembly head project, you'll need to include the assembly name in the LinkerConfig.xml file.
For example:
<linker>
<assembly fullname="MyProject.Wasm" />
<assembly fullname="MyOtherLibrary" />
<assembly fullname="System.Core">
<!-- This is required by Json.NET and any expression.Compile caller -->
<type fullname="System.Linq.Expressions*" />
</assembly>
</linker>
Using Microsoft.EntityFrameworkCore.SQLite, I'm attempting to create a code level creation of a database, and add a simple row to a table. I get the error, SQLite error: no such table Jumplists.
From last to first, here are the classes
using JumpList_To_Clipboard.Data.Tables;
using Microsoft.EntityFrameworkCore;
namespace JumpList_To_Clipboard.Data
{
public class DataSQLite : IData
{
public const string DATABASE = "data.sqlite";
public DataSQLite()
{
using (var db = new SQLiteDbContext(DATABASE))
{
// Ensure database is created with all changes to tables applied
db.Database.Migrate();
db.JumpLists.Add(new JumpList { Name = "Default" });
db.SaveChanges(); // Exception thrown here
}
}
}
}
The DbContext class
using JumpList_To_Clipboard.Data.Tables;
using Microsoft.EntityFrameworkCore;
namespace JumpList_To_Clipboard.Data
{
class SQLiteDbContext : DbContext
{
readonly string db_path;
public DbSet<JumpList> JumpLists { get; set; }
public DbSet<Group> Groups { get; set; }
public DbSet<Item> Items { get; set; }
public SQLiteDbContext(string database) : base()
{
db_path = database;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite(string.Format("Data Source={0}", db_path));
}
}
}
The JumpList class
using System.Collections.Generic;
namespace JumpList_To_Clipboard.Data.Tables
{
public class JumpList
{
public int JumpListId { get; set; }
public string Name { get; set; }
public List<Group> Groups { get; set; }
public List<Item> Items { get; set; }
}
}
The other two classes aren't worth repeating here, and don't give errors.
When I use the firefox sqlite extension to look at the data.sqlite file, none of my three tables are listed.
The command db.DataBase.Migrate says it
Applies any pending migrations for the context to the database.
What are pending migrations? I can't seem to find any documentation anywhere on these.
I'm combining examples from:
https://learn.microsoft.com/en-us/ef/core/get-started/netcore/new-db-sqlite
https://blogs.msdn.microsoft.com/dotnet/2016/09/29/implementing-seeding-custom-conventions-and-interceptors-in-ef-core-1-0/
Edit: If I replace db.Database.Migrate(); with db.Database.EnsureCreated(); it works. From the documentation, Migrate() is the same, but lets you create updates to the table structures, where EnsureCreated() does not. I'm confused.
So,
Microsoft has a serious issue making decent documentation, but I did find a site that has somewhat dated documentation for Learning Entity Framework Core, specifically migrations which is in the link.
At the top, it mentions,
If you have Visual Studio, you can use the Package Manager Console (PMC) to manage migrations.
Which led to the Package Manager Console page which states right at the top, that you need to have:
If you want to use the Package Manager Console to execute migrations command, you need to ensure that the latest version of Microsoft.EntityFrameworkCore.Tools is added to your project.json file.
The problem is, there is no project.json file anywhere in my project (or solution). After some searching, I found that via NuGet, to add Microsoft.EntityFrameworkCore.Tools
Then via Tools > NuGet Package Manager > Package Manager Console I was able to run the add-migration InitialDatabases command. The last part InitialDatabases is the name of the class it creates for you, and sticks in a folder called Migrations at the base of the project.
Now when:
context.Database.Migrate();
is run, all is well!
Try this (worked for me in a project a few months ago, i don't remember why):
public virtual DbSet<JumpList> JumpLists { get; set; }
public virtual DbSet<Group> Groups { get; set; }
public virtual DbSet<Item> Items { get; set; }
Also i had to use LONG instead of INT for classes ID because sqlite uses LONG as default for table ID, so after when you do a CRUD operation it fails because it can't compare/convert/cast LONG(64) to INT(32).
I've been doing BI project management work for several years and coming back into some web app dev work now. I am building an asp.net core app and using EF core. Lazy loading isn't enabled on EF Core, which is fine. I think I want to use .Include to load a related object.
So if you have
public class Customer {
public int CustomerId { get; set; }
public Address { get; set; }
}
public ViewResult List()
{
CustomerListViewModel customersListViewModel = new CustomerListViewModel();
customersListViewModel.Customers = _customerRepository.Customers.??? // Include does not resolve...
return View(customersListViewModel);
}
I am trying to return an IEnumbable of Customers that eagerly loads the Address as well. The other answers suggest I should be able to use .Include() but that doesn't seem to be an available method for me.