I have implemented the DbContext in my project. I used the inheritance using the TPC Approach of entity framework. When I run the code to fetch the database record it throw an exception.
[Added the class structure with exception message]
When I use the Entity framework to get the user by providing the 'UserDefault user' user.Login & user.Password, it provide me the user details, but When I do navigate to user.Roles to check the roles, it throws the exception [Added below]:
already use the Table Attribute & Plurization Error at model binding etc.
//DbContext Class
public class Db : DbContext
{
public Db()
{
Database.SetInitializer<Db>(null);
}
public DbSet<Roles> Roles { get; set; }
public DbSet<UserDetails> UserDetails { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<UserDetails>()
.ToTable("UserDetails")
.HasMany(r => r.Roles).WithMany(o => o.UserDetails)
.Map(f =>
{
f.MapLeftKey("UserId");
f.MapRightKey("RoleId");
});
modelBuilder.Entity<Roles>().ToTable("Roles");
}
}
//User Details Model
[Table("UserDetails", Schema = "dbo")]
public partial class UserDetails : DelEntity
{
public string Title { get; set; }
public string Name { get; set; }
public string Login { get; set; }
public string Password { get; set; }
public string PreferName { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostCode { get; set; }
public string Country { get; set; }
public string CountryCode { get; set; }
public string DateofBirth { get; set; }
public string Gender { get; set; }
public string Nationality { get; set; }
public string DateofJoining { get; set; }
public string DateofLeaving { get; set; }
public string Language { get; set; }
public Nullable<long> OrganizationId { get; set; }
public Nullable<long> BranchId { get; set; }
public Nullable<long> DepartmentId { get; set; }
public string PhoneNumber { get; set; }
public string PhoneExtension { get; set; }
public string FaxNumber { get; set; }
public string HomeNumber { get; set; }
public string EmailAddress { get; set; }
public string OtherReference { get; set; }
public virtual ICollection<Roles> Roles { get; set; }
}
//Role Model
[Table("Roles", Schema = "dbo")]
public class Roles : Entity
{
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<UserDetails> UserDetails { get; set; }
}
//DelEntity Model
public class DelEntity : Entity, IDel
{
//[Column("IsDeleted")]
public bool IsDeleted { get; set; }
}
//Entity Model
public class Entity
{
//[Key]
//[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
//[Column("Id")]
public int Id { get; set; }
}
//IDEL Interface
public interface IDel
{
bool IsDeleted { get; set; }
}
ex.Message : An error occurred while executing the command definition. See the inner exception for details.
ex.InnerMessage : {System.Data.SqlClient.SqlException (0x80131904): Invalid object name 'dbo.UserDetailsRoles'.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
at System.Data.SqlClient.SqlDataReader.get_MetaData()
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<>c__DisplayClassb.<Reader>b__8()
at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TInterceptionContext,TResult](Func`1 operation, TInterceptionContext interceptionContext, Action`1 executing, Action`1 executed)
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)
at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
ClientConnectionId:c965de15-d3cf-467c-9e19-866cd35a9400
Error Number:208,State:1,Class:16}'
I have create the 'Roles' table in my database while the code is trying to fetch the 'dbo.UserDetailsRoles'. I have use the Table Attribute in class & modelBuilder.Entity().ToTable("Roles"); in DbContext class but still it is looking for UserDetailsRoles table. Here UserDetails is my other table which is associated with Roles.
Once I check with below code:
var context = new Db();
!context.Database.Exist()
{
//Created Roles and save into Db
//Created User and save into Db
//get successfully the user.Id using where clause
//get successfully the role.Id using where clause
}
//exit the method
I noticed that It creates an UserDetailsRoles table and save the setting of UserId and RoleId specified in OnModelCreating in Db class.
Code snippets:
modelBuilder.Entity<UserDetails>()
.ToTable("UserDetails")
.HasMany(r => r.Roles).WithMany(o => o.UserDetails)
.Map(f =>
{
f.MapLeftKey("UserId");
f.MapRightKey("RoleId");
});
Is there any way I can change the name of this table?? [for UserId & RoleId columns's table]
User contributions licensed under CC BY-SA 3.0