I have a model as below :
public class BaseModel
{
public DateTime? CrDate { get; set; }
[ForeignKey("CrUser")]
public ApplicationUser UserCr { get; set; }
public string CrUser { get; set; }
public DateTime? MdDate { get; set; }
[ForeignKey("MdUser")]
public ApplicationUser UserMd { get; set; }
public string MdUser { get; set; }
public bool IsDeleted { get; set; }
public void LogWhatever()
{
this.CrDate = System.DateTime.Now;
this.CrUser = ?????
}
}
How can i get the logged userID from model to store in CrUser ?
regards.
Asp.net Identity expose IUser(IdentityUser) Context, once user logged in.
Context.User.Identity.GetUserId()
Related
How do I map table value functions in Code with Entity Framework 6.3? I'm trying to a DB Context in code with an existing database, because EDMX is currently not supported in ASP.NET Core 3. I've tried setting up my DbContext clasee as below. I can successfully query the Grade table. But when I try to query my function "fn_GetCatgeories", I get the following error: No EdmType found for type 'WebApplication6.Data.ApplicationContext+fn_GetCategories'.
public class ApplicationContext : DbContext
{
public ApplicationContext(string cstr)
: base(cstr)
{
Database.SetInitializer<ApplicationContext>(null);
}
[Table("Grade")]
public class Grade
{
[Key]
public string Grade_ID { get; set; }
public string SchoolType { get; set; }
public int Sortorder { get; set; }
}
public partial class fn_GetCategories
{
public int Category_ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public Nullable<bool> Active { get; set; }
public Nullable<System.DateTime> Month { get; set; }
public Nullable<int> Order { get; set; }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Add(new FunctionsConvention<ApplicationContext>("dbo"));
base.OnModelCreating(modelBuilder);
}
[DbFunction("ApplicationContext", "fn_GetCategories")]
public IQueryable<fn_GetCategories> GetCategories(Nullable<System.DateTime> month)
{
var monthParameter = month.HasValue ?
new ObjectParameter("Month", month) :
new ObjectParameter("Month", typeof(System.DateTime));
return ((IObjectContextAdapter)this).ObjectContext.CreateQuery<fn_GetCategories>(string.Format("[0].{1}", GetType().Name, "[fn_GetCategories](#Month)"), monthParameter);
}
// DbSets here
public DbSet<Grade> Grades { get; set; }
}
This works:
public class ApplicationContext : DbContext
{
public ApplicationContext(string cstr)
: base(cstr)
{
Database.SetInitializer<ApplicationContext>(null);
}
[Table("Grade")]
public class Grade
{
[Key]
public string Grade_ID { get; set; }
public string SchoolType { get; set; }
public int Sortorder { get; set; }
}
public partial class fn_GetCategories_Result
{
[Key]
public int Category_ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public Nullable<bool> Active { get; set; }
public Nullable<System.DateTime> Month { get; set; }
public Nullable<int> Order { get; set; }
}
// DbSets here
public DbSet<Grade> Grades { get; set; }
public DbSet<fn_GetCategories_Result> fn_GetCategoriesSet { get; set; }
public List<fn_GetCategories_Result> fn_GetCategories(DateTime month)
{
var m = new SqlParameter("Month", DateTime.Now);
return this.fn_GetCategoriesSet.SqlQuery("select * from dbo.fn_GetCategories(#month)", m).ToList();
}
I have asked question in a different post, but seems that was not the right question, so going to reword here:
I have three classes:
public class StateLog : BaseModel
{
public Guid StateLogId { get; set; }
public Guid LookupMasterId { get; set; }
public Guid EntityId { get; set; }
public string Discriminator { get; set; }
public bool IsActive { get; set; }
public virtual LookupMaster State { get; set; }
}
Second class:
public class ApplicationState : StateLog
{
[Column("EntityId")]
public Guid ApplicationId { get; set; }
}
There is another Class DocumentStates which inherits from StateLog.
Application:
public class Application : BaseModel
{
public Guid ApplicationId { get; set; }
public Guid UserId { get; set; }
public virtual User User { get; set; }
[Required]
public Guid ApplicationTypeId { get; set; }
public bool? AuthorizedToWork { get; set; } = false;
public string Token { get; set; }
public string ApplicationTitle { get; set; }
public string WorkStartDate { get; set; }
public Nullable<DateTime> SignedAt { get; set; } = DateTime.Now;
public bool? Signed { get; set; }
public string Notes { get; set; }
public virtual ICollection<ApplicationSelfDeclaration> ApplicationSelfDeclarations { get; set; }
public virtual ICollection<ApplicationState> ApplicationStates { get; set; }
public virtual ICollection<StateLog> StateLogs { get; set; }
}
I am trying to save statelogs for both application and documents in same table and based on Discriminator, fetch data.
E.g.
_context.Applications.include(a => a.ApplicationState)
This is not not working. ApplicationState should Alias EntityId column as ApplicationId. But it is not working.
Any idea what my options are at this point?
Thanks in advance.
I have two model classes:
Request:
public partial class Request
{
public long Id { get; set; }
public string Username { get; set; }
public string Description { get; set; }
public System.DateTime CreateDate { get; set; }
public long DeviceId { get; set; }
public bool IsFinalized { get; set; }
public Nullable<long> ParentId { get; set; }
public virtual Device Device { get; set; }
}
Device:
public partial class Device
{
public Device()
{
this.Requests = new List<Request>();
}
public long Id { get; set; }
public string Serial { get; set; }
public string AssetNumber { get; set; }
public System.DateTime CreatedDate { get; set; }
public virtual ICollection<Request> Requests { get; set; }
}
I have to update the models I use this method
public void Update(RequestViewModel viewModel)
{
var entity = _mappingEngine.Map<Request>(viewModel);
_requests.Attach(entity);
_uow.Entry(entity).State = EntityState.Modified;
}
but only Request model is updated after calling the Update method. I want to update both models. Please help me.
Attaching an entity to a DbContext, mark the attached entity and all its dependencies (i.e. associated entities) UnChanged. So its you who must tell EF what entities are new and what entities were modified.
I'm using asp.net mvc 4, EF, codefirst to make a many to many relation to a users and roles system
the user model:
public class User
{
#region properties
[Key]
public Int32 Id { get; set; }
[Required]
public String UserName { get; set; }
public String Password { get; set; }
[Required]
public String Email { get; set; }
public DateTime CreationDate { get; set; }
public DateTime LastUpdate { get; set; }
public DateTime? LastLogin { get; set; }
[ForeignKey("RoleId")]
public virtual ICollection<Role> Roles { get; set; }
#endregion //properties
#region constructors
public User()
{
Roles = new HashSet<Role>();
LastUpdate = DateTime.Now;
CreationDate = DateTime.Now;
}
#endregion //constuctors
}
the role model:
public class Role
{
[Key]
public Int32 Id { get; set; }
public String Name { get; set; }
public String Description { get; set; }
public DateTime CreationDate { get; set; }
public DateTime LastUpdate { get; set; }
[ForeignKey("UserId")]
public virtual ICollection<User> Users { get; set; }
public Role()
{
Users = new HashSet<User>();
CreationDate = DateTime.Now;
LastUpdate = DateTime.Now;
}
}
the context:
public class UserManagementContext : Context, IContext
{
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
public UserManagementContext() {
Database.SetInitializer<UserManagementContext>(null);
}
void IContext.Setup(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().ToTable("Users");
modelBuilder.Entity<Role>().ToTable("Roles");
modelBuilder.Entity<User>()
.HasMany(u => u.Roles)
.WithMany(r => r.Users)
.Map(
m =>
{
m.MapLeftKey("UserId");
m.MapRightKey("RoleId");
m.ToTable("UserRoles");
});
}
}
When the database tables are generated the tables users, roles and userroles are there. Then I make a record in users, one in roles and one in userroles to connect those. The userroles table has two columns RoleId and UserId.
Then I try to load the roles of a user like this:
public String[] GetRoles(String userName)
{
//var user = ConcreteContext.Users.Include("Roles").Where(u => u.UserName == userName).FirstOrDefault();
var users = ConcreteContext.Users.Include(u => u.Roles);
var user = users.FirstOrDefault();
var roles = from r in user.Roles
select r.Name;
return roles.ToArray();
}
But the line with var users = ConcreteContext.Users.Include(u => u.Roles); raises the next error:
System.Data.SqlClient.SqlException: Invalid object name 'dbo.RoleUsers'.
If I change de table name of UserRoles to RoleUsers when de database is created (by using m.ToTable(RoleUsers) ), I get a lot of different errors about wrong field names.
Anyone an idea what I'm missing here?
Thanks in advance,
Willem
Any reason why you have to use the Fluent API?
You can map Many-to-many like this with data attributes:
public class User
{
[InverseProperty( "Users" )]
public virtual ICollection<Role> Roles {get;set;}
}
public class Role
{
[InverseProperty( "Roles" )]
public virtual ICollection<User> Users {get;set;}
}
This will do what I needed:
public class User
{
#region properties
[Key]
public Int32 Id { get; set; }
[Required]
public String UserName { get; set; }
public String Password { get; set; }
[Required]
public String Email { get; set; }
public DateTime CreationDate { get; set; }
public DateTime LastUpdate { get; set; }
public DateTime? LastLogin { get; set; }
[InverseProperty("Users")]
public virtual ICollection<Role> Roles { get; set; }
#endregion //properties
#region constructors
public User()
{
LastUpdate = DateTime.Now;
CreationDate = DateTime.Now;
}
#endregion //constuctors
}
public class Role
{
[Key]
public Int32 Id { get; set; }
public String Name { get; set; }
public String Description { get; set; }
public DateTime CreationDate { get; set; }
public DateTime LastUpdate { get; set; }
[InverseProperty("Roles")]
public virtual ICollection<User> Users { get; set; }
public Role()
{
CreationDate = DateTime.Now;
LastUpdate = DateTime.Now;
}
}
public class UserManagementContext : Context, IContext
{
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
public UserManagementContext() {
Database.SetInitializer<UserManagementContext>(null);
}
void IContext.Setup(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().ToTable("Users");
modelBuilder.Entity<Role>().ToTable("Roles");
}
}
Is it possible to automap UserViewModel to User?
public class User
{
[Key]
public virtual int UserId { get; set; }
public virtual string Name { get; set; }
public virtual string Surname { get; set; }
[Required]
public virtual string Username { get; set; }
[Required]
public virtual string Password { get; set; }
public virtual ICollection<Role> Roles { get; set; }
}
public class UserViewModel
{
public User User { get; set; }
public List<Role> AvailableRoles { get; set; }
public List<Role> AssignedRoles { get; set; }
public int[] AvailableSelected { get; set; }
public int[] AssignedSelected { get; set; }
public string SavedAssigned { get; set; }
}
AutoMapper.Mapper.CreateMap<UserViewModel, User>();
AutoMapper.Mapper.Map(model, user);
I've tried this, but it won't work. I need it for my Edit action method in the User controller to save the changes to the database.
Have you tried
AutoMapper.Mapper.CreateMap<UserViewModel, User>()
.ForMember(dest => dest, opt => opt.MapFrom(src => src.User));