Reputation: 5294
I'm struggling a bit to adding a schema to a table attribute in EF Core. When running ado.net the following works fine:
private static void Reademps()
{
string sql = "SELECT [Id],[empno] FROM [encrypt].[dbo].[emps]";
var connection = new SqlConnection(connectionString);
var command = new SqlCommand(sql, connection);
connection.Open();
using (SqlDataReader reader = command.ExecuteReader(System.Data.CommandBehavior.CloseConnection))
{
while (reader.Read())
{
Console.WriteLine($"id: {reader[0]} empno: {reader[1]}");
}
}
}
However trying to convert to EF Core:
private async Task ReadempsAsync()
{
using (var context = new EmpsContext())
{
List<Emp> emps = await context.Emps.ToListAsync();
foreach (var b in emps)
{
Console.WriteLine($"{b.Id} {b.Empno}");
}
}
}
internal class EmpsContext : DbContext
{
private const string ConnectionString = @"server=localhost\SQLEXPRESS;Database=master;Integrated security=true;Database=master;Column Encryption Setting=enabled";
public DbSet<Emp> Emps { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
optionsBuilder.UseSqlServer(ConnectionString);
}
}
[Table("emps", Schema = "encrypt")]
public class Emp
{
public int Id { get; set; }
[Required]
[StringLength(50)]
public string Empno { get; set; }
}
I keep getting an error:
System.Data.SqlClient.SqlException: 'Invalid object name 'encrypt.emps'.'
Upvotes: 2
Views: 5045
Reputation: 943
You have to just use "dbo"
for Schema because of encrypt
is not schema name. It is just database
name. It will be like this:
[Table("emps", Schema = "dbo")]
public class Emp
{
public int Id { get; set; }
[Required]
[StringLength(50)]
public string Empno { get; set; }
}
NOTE:
In your connection string change Database
to encrypt
. Your connection string will be like:
private const string ConnectionString = @"server=localhost\SQLEXPRESS;Database=encrypt;Integrated security=true;Column Encryption Setting=enabled";
Upvotes: 4
Reputation: 754478
In your SQL - [encrypt]
appears to be the database name - not the schema name (that would be the dbo
in the middle).
SELECT [Id],[empno] FROM [encrypt].[dbo].[emps]
********* ***** ******
* * * Table Name
* * Schema name
* Database name
So your EF Core table declaration is wrong since it defines the schema to be encrypt
- but that's not the case.
So this:
[Table("emps", Schema = "encrypt")]
public class Emp
should really be:
[Table("emps", Schema = "dbo")]
**************
public class Emp
Upvotes: 3