EF Core Oracle table does not exist error - oracle

I am using Dot Net Core 3.1 , EF Core and Oracle.EntityframeworkCore
Steps I followed :
Created a table named "USER" in Oracle using Toad , with following DDL statement
CREATE TABLE POLICYAPP.USER {
ID NUMBER GENERATED BY DEFAULT AS IDENTITY,
USERNAME VARCHAR2(10) NOT NULL,
PASSWORDHASH VARCHAR2(30) NOT NULL
PRIMARY KEY(ID)
};
where the schema name is "POLICYAPP"
Verified that the table "USER" is present in the schema "POLICYAPP"
Created Dot net Core WebAPI project in Visual Studio 2019
Created "Models" folder and created class "User.cs" with below definition
[Table("USER", Schema = "POLICYAPP")]
public class User
{
[key]
[column("ID")]
public int id {get; set;}
[column("USERNAME")]
public string username {get; set;}
[column("PASSWORDHASH")]
public string passwordhash {get; set;)
}
Create AppDbContext class that contains following
public DbSet Users {get; set;}
Created "Repositories" folder and created interface "IAuthRepository" with method findByUsername
Also, created class "AuthRepository" that implements the interface "IAuthRepository" using LINQ query
Modified Startup.cs to include following in ConfigureServices method
var connstring = Configuration.GetConnectionString("poldb");
services.AddDbContext<AppDbContext> {
options => options.useOracle(connstring)
};
services.AddScoped<IAuthRepoistory, AuthRepository>;
The file appsettings.json has proper connection string.
Created "Controllers" folder and created class "AuthController" in the folder
The controller invokes the repository find method to search by username
The issue is :
When I run the app and enter url http:\localhost:10220\api\Authn\John, it fails with error
"OracleException: ora-00942 table or view does not exist"
Added below code in AppDbContext.cs , still get the same error
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("POLICYAPP");
}

Related

EF Core 5 code inheritance without database inheritance #26741

I have two EF models:
public class Child: BaseClass
{
public string SomeProp {get; set;}
}
[Table("TableName")]
public absctract class BaseClass
{
public int ID {get; internal set;}
... some other properties and navigation collections...
}
I have only one table "TableName" with all columns from "BaseClass" and "Child" classes and I would use 'Child' type to access the table.
But, when i've tried to do it, i got exception: "Invalid column name 'Discriminator'."
With EF 6, I was able to do it.
Discriminator is how EF Core differentiates the .Net types in the hierarchy.
Check out the table per heirarchy section in these articles:
https://learn.microsoft.com/en-us/ef/core/modeling/inheritance#table-per-hierarchy-and-discriminator-configuration
https://blogs.dhrutara.com/blogs/efcore5-migrations-with-inheritance/

asp.net mvc adding custom column to identity role table

This is how I add new column to Identity role table
public class ApplicationRole : IdentityRole
{
public ApplicationRole() : base() { }
public ApplicationRole(string name, long customId) : base(name)
{
this.CustomId= customId;
}
public virtual long CustomId{ get; set; }
}
In dbContext , I added
modelBuilder.Entity<ApplicationRole>().ToTable("AspNetRoles");
using this , new column CustomId is added successfully to AspNetRoles table using migration .
But when I have to call role table like
private readonly IdentityDbContext db_Identity;
..
..
db_Identity.Roles.Select(x=>x.CustomId)
I can't find newly added column CustomId here .
Is there any step I missed ?
Update
With #Chirs's answer , I can get CoustomId , but when I run , I got this error
Cannot create a DbSet for 'IdentityRole' because this type is not included in the model for the context
If you are using custom Identity models, you also need to inherit from one of the generic IdentityDbContext classes and specify your custom type in the appropriate type param. In this case, you just need something like:
public class MyDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string>
Then use your custom context class:
private readonly MyDbContext db_Identity;

Initial migration source file does not contain schema for database

I am using entity framework 6 with Web API. I have applied Enable-Migrations command in package manager console and Migration folder created with Configuration class.
I have executed Add-Migration -InitialCreate command initial migration source file created but up and down methods are empty.
so when I recreate the database no table is created except migrationhistory table. No table is created into database so my API cannot perform any POST, GET operation and getting below error message.
Exception type: System.Data.SqlClient.SqlException
Message : Invalid object name 'dbo.Template'.
Please assist me.
I have put my connection string in database.config in startup project not in Web.config of startup project reason behind this was I didn't want to start Web API when database name changes in Web.config. I have attached my Web.config snapshot.
MigrationHistory Table
Below is code for DBContext class.
public class TestDBContext : DbContext
{
public DbSet<SamlNode> SamlNodes { get; set; }
public DbSet<Template> Templates { get; set; }
private static string connectionString
{
get
{
Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpRuntime.AppDomainAppVirtualPath);
ConnectionStringsSection connectionString = (ConnectionStringsSection)config.GetSection("database");
if (connectionString != null && connectionString.ConnectionStrings["TestDBContext"] != null)
{
return connectionString.ConnectionStrings["TestDBContext"].ConnectionString;
}
}
}
public TestDBContext()
: base(connectionString)
{
Database.SetInitializer<TestDBContext>(new CreateDatabaseIfNotExists<TestDBContext>());
//Database.SetInitializer(new MigrateDatabaseToLatestVersion<TestDBContext, Migrations.Configuration>(connectionString));
}
protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
Regards,
Rashi

Additional column in query generated by Entity Framework

I am using EF5 and .NET 4.5 targeting an Oracle 11g database through Oracle.ManagedDataAccess.Client. I set up a small table to test and the how it works.
Now here is a weird fact which shows no result on searching the web nor this site. On every query I have a last column like "Extent1"."Text_TextID"!!! This obviously makes Oracle to throw an error Invalid identifier as I have no column with such name nor another object in the database.
This happens no matter how many tables/columns I have and no matter how I name them (if I have several tables all will have this extra column in the query).
Anybody has any idea why this happens??
Sample code below:
//POCO class and mapping
[Table("LO_USERS")]
public class User
{
[Key]
[Column("USER_ID")]
public int UserID { get; set; }
}
//define the context
public class TestContext : DbContext
{
public TestContext():base("OracleConn")
{
}
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//replace the annoying dbo schema name. Note: even if I remove this, I still get the extra column in the query
modelBuilder.Entity<User>().ToTable("LO_USERS", "TEST_SCHEMA");
}
//create a new user
using (var db = new TestContext())
{
var user = new User();
db.Users.Add(user);
//here I set a breakpoint
db.SaveChanges();
}
The query as showing by VS2012 at the breakpoint:
SELECT
1 AS "C1",
CAST( "Extent1"."USER_ID" AS number(10,0)) AS "C2",
"Extent1"."Text_TextID" AS "Text_TextID"
FROM "TEST_SCHEMA"."LO_USERS" "Extent1"
Edit:
It is the same with EF6 and DotConnect.
I found it: the problem was I was referencing User class in another class as child object, like
public class Text
{
public virtual ICollection<User> Users { get; set; }
without specifying any foreign key column in user class and EF was trying to set one by its own.
Once I removed the line above the extra column disappeared from the select statement.

Trying to use Entity Framework with asp.net MVC3

I'm trying to make EntityFramework work with ASP .NET MVC3 using this tutorial:
http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application
Ok, I have my database, my .edmx model, model classes but one first thing I don't get is:
How does my DbContext derived class even know my .emdx model ? I don't fine where the "link" is created in this tutorial (maybe having several thing with the same name "SchoolContext", for the context as for the connexionstring is confusing ...)
When I run what I got for now with the code:
MMContext context = new MMContext();
List<EntityUser> testList = (from u in context.Users
select u).ToList();
I get:
System.Data.Edm.EdmEntityType: : EntityType 'EntityUser' has no key defined. Define the key for this EntityType.
System.Data.Edm.EdmEntitySet: EntityType: EntitySet �Users� is based on type �EntityUser� that has no keys defined.
Thank you for your help.
Assuming you are using the Code-First approach, you have to define a Key in your Users class:
public class User
{
public int Id { get; set; }
// ...
}
As mentioned from Kyle, if your ID field is not named "Id" you have to add the [Key] attribute:
using System.ComponentModel.DataAnnotations;
public class User
{
[Key]
public int u_Id { get; set; }
// ...
}

Resources