I'm getting the following error when running my application. I'm forcing the application to do a DropCreateDatabaseAlways for my context so I'm not sure why it would say that I'm trying to insert multiple entities with the same key.
There might be a problem with how User and Message are linked. I had to add:
modelBuilder.Entity<Message>()
.HasRequired(m => m.UserSentFrom)
.WithRequiredDependent()
.WillCascadeOnDelete(false);
Just because I was getting a warning about circular reference and had to set the willcascadeondelete to false.
If there is something wrong with my design, let me know, but this is what I'm trying to do:
User has many Messages,
Message has one FromUser
Message has many ToUsers
Any help will be appreciated as this is driving me crazy.
{"Conflicting changes detected. This may happen when trying to insert multiple entities with the same key."}
public class User
{
public int Id { get; set; }
[Required(ErrorMessage="Username is required")]
public string Username { get; set; }
[Required(ErrorMessage = "Password is required")]
[DataType(DataType.Password)]
public string Password { get; set; }
[Required(ErrorMessage="Email Address is required")]
[DataType(DataType.EmailAddress)]
public string UserEmailAddress { get; set; }
[DisplayFormat(DataFormatString="{0:d}",ApplyFormatInEditMode=true)]
public DateTime DateCreated { get; set; }
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime LastUpdated { get; set; }
public virtual ICollection<Message> Messages { get; set; }
public User()
{
Messages = new List<Message>();
}
}
public class Message
{
public int Id { get; set; }
public DateTime DateSent { get; set; }
public virtual ICollection<User> UserSentTo { get; set; }
public string Title { get; set; }
public string Body { get; set; }
public int UserSentFromId { get; set; }
public virtual User UserSentFrom { get; set; }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Message>()
.HasMany(m => m.UserSentTo).WithMany(u => u.Messages)
.Map(t => t.MapLeftKey("MessageId")
.MapRightKey("UserId")
.ToTable("MessagesUserSentTo"));
modelBuilder.Entity<Message>()
.HasRequired(m => m.UserSentFrom)
.WithRequiredDependent()
.WillCascadeOnDelete(false);
}
protected override void Seed(WebsiteGameContext context)
{
var users = new List<User>
{
new User { Username = "Admin", UserEmailAddress="admin#temp.com", DateCreated = DateTime.Now, LastUpdated = DateTime.Now},
new User { Username = "Member", UserEmailAddress="member#temp.com",DateCreated = DateTime.Now, LastUpdated = DateTime.Now}
};
users.ForEach(u => context.Users.Add(u));
context.SaveChanges();
var messages = new List<Message>
{
new Message { DateSent=DateTime.Now, Title="Sent From Admin", Body="There should be 2 users that this was sent to", UserSentFromId=users[0].Id,UserSentTo= new List<User>()},
new Message { DateSent=DateTime.Now, Title="Sent From Member", Body="There should be 1 user that this was sent to", UserSentFromId=users[1].Id,UserSentTo= new List<User>()}
};
messages.ForEach(m => context.Messages.Add(m));
context.SaveChanges();
messages[0].UserSentTo.Add(users[0]);
messages[0].UserSentTo.Add(users[1]);
messages[1].UserSentTo.Add(users[0]);
context.SaveChanges();
}
To make it work change 2 things.
First delete the messages property in Users and make a MessagesSend and MessagesReceived property. Then make the mapping like this:
modelBuilder.Entity<Message>().HasMany(t => t.UserSentTo)
.WithMany(t => t.MessagesReceived)
.Map(m =>
{
m.ToTable("MessagesUserSentTo");
m.MapLeftKey("MessageId");
m.MapRightKey("UserId");
});
modelBuilder.Entity<Message>().HasRequired(t => t.UserSentFrom)
.WithMany(t => t.MessagesSend)
.HasForeignKey(d => d.UserSentFromId)
.WillCascadeOnDelete(false);
Related
Using .Net Core 2.1 and Audit.NET EF 12.1.10, I'm trying to add a migration that includes the audit tables but when invoking Add-Migration, no audit tables are generated in the migration. I assumed that using the "dynamic" audit will do this automagically. I don't have any audit interfaces-- I am leaving this up to Audit.NET. Below is in my Startup:
var serviceProvider = services.BuildServiceProvider();
Audit.EntityFramework.Configuration.Setup()
.ForContext<MainDbContext>(config => config
.IncludeEntityObjects()
.AuditEventType("{context}:{database}"))
.UseOptOut()
.IgnoreAny(entity => entity.Name.StartsWith("AspNet") && entity.Name.StartsWith("OI"));
Audit.Core.Configuration.Setup()
.UseEntityFramework(ef => ef
.AuditTypeNameMapper(typeName => "Audit_" + typeName)
.AuditEntityAction((evt, entry, auditEntity) =>
{
// Get the current HttpContext
var httpContext = serviceProvider.GetService<IHttpContextAccessor>().HttpContext;
// Store the identity name on the "UserName" property of the audit entity
((dynamic)auditEntity).UserName = httpContext.User?.Identity.Name;
((dynamic)auditEntity).AuditDate = DateTime.UtcNow;
((dynamic)auditEntity).AuditAction = entry.Action;
}));
My DbContext extending from AuditIdentityDbContext:
public class MainDbContext : AuditIdentityDbContext<User, Role, string>
I only have one entity so far, called Activity, just to test this out and I would expect Add-Migrations to include an Audit_Activity table as well as the Activity table, but I only got the latter. Not sure what I'm doing wrong here.
I tried Auditing Identity Roles just because it was easiest to test at the moment
public class ApplicationRole : IdentityRole
{
}
public class Audit_ApplicationRole : IAudit
{
[Key]
public string Id { get; set; }
[Column(TypeName = "NVARCHAR(256)")]
public string Name { get; set; }
[Column(TypeName = "NVARCHAR(256)")]
public string NormalizedName { get; set; }
public string ConcurrencyStamp { get; set; }
public ApplicationRole Role { get; set; }
public string RoleId { get; set; }
[Column(TypeName = "VARCHAR(100)")]
public string AuditUser { get; set; }
public DateTime AuditDate { get; set; }
[Column(TypeName = "VARCHAR(7)")]
public string Action { get; set; } // "Insert", "Update" or "Delete"
}
public interface IAudit
{
string AuditUser { get; set; }
DateTime AuditDate { get; set; }
string Action { get; set; }
}
Then I used your code in StartUp.cs
Audit.EntityFramework.Configuration.Setup()
.ForContext<ApplicationDbContext>(config => config
.IncludeEntityObjects()
.AuditEventType("{context}:{database}"));
Audit.Core.Configuration.Setup()
.UseEntityFramework(x => x
.AuditTypeNameMapper(typeName => "Audit_" + typeName)
.AuditEntityAction<IAudit>((ev, ent, auditEntity) =>
{
auditEntity.AuditDate = DateTime.UtcNow;
auditEntity.AuditUser = ev.Environment.UserName;
auditEntity.Action = ent.Action;
}));
What I found out is that the Id had to be string for some reason, it could not be int.
Screenshot from the link shows that the changes in data have saved.
enter image description here
On the side note, I wanted to save the user logged in via Identity, so in case anyone wondering, this post helped me achieve it.
https://entityframeworkcore.com/knowledge-base/49799223/asp-net-core-entity-changing-history
I need your help on this. I always get the error "Invalid column name 'Discriminator'" every time I do a select. What's weird is that, I don't have any Discriminator column in my mapping or in my table. I tried adding the [NotMapped] in my class (as mentioned here: EF Code First “Invalid column name 'Discriminator'” but no inheritance) but to no avail.
Below are my codes which triggered the error.
Model
public class MasterUser : IAuditFields
{
[Key]
public string Username { get; set; }
public string Name { get; set; }
public string GroupID { get; set; }
public string Status { get; set; }
public string DeptID { get; set; }
public string Rank { get; set; }
public string CreatedBy { get; set; }
[Required]
public DateTime CreatedDate { get; set; }
public string LastModifiedBy { get; set; }
public DateTime? LastModifiedDate { get; set; }
#region Relationships
public UserAccess UserAccess { get; set; } // User needs to see what user access group he/she is in
public UserAccessDetail UserAccessDetail { get; set; } //User needs to see what he/she can do
#endregion
}
Interface
public interface IAuditFields
{
string CreatedBy { get; set; }
DateTime CreatedDate { get; set; }
string LastModifiedBy { get; set; }
DateTime? LastModifiedDate { get; set; }
}
Configuration class
public class MasterUserConfig : EntityTypeConfiguration<MasterUser>
{
public MasterUserConfig()
{
Property(usr => usr.Username)
.HasColumnName("UserName")
.IsRequired();
Property(usr => usr.Name).HasColumnName("Name");
Property(usr => usr.GroupID).HasColumnName("GroupId");
Property(usr => usr.Status).HasColumnName("Status");
Property(usr => usr.DeptID).HasColumnName("DeptId");
Property(usr => usr.Rank).HasColumnName("Rank");
Property(usr => usr.CreatedBy).HasColumnName("CreatedBy");
Property(usr => usr.CreatedDate).HasColumnName("CreatedDate");
Property(usr => usr.LastModifiedBy).HasColumnName("LastModifiedBy");
Property(usr => usr.LastModifiedDate).HasColumnName("LastModifiedDate");
ToTable("dbo.Users");
}
DataContext
public class BBDataContext : DbContext
{
public DbSet<MasterUser> Users { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
try
{
modelBuilder.Configurations.Add(new MasterUserConfig());
base.OnModelCreating(modelBuilder);
}
catch (Exception ex)
{
DiagnosticHelper.Message = ex.Message;
DiagnosticHelper.InnerException = ex.InnerException.Message;
DiagnosticHelper.StackTrace = ex.StackTrace;
DiagnosticHelper.Instance.WriteError();
}
}
}
Select method
public MasterUser GetUserByUsername(string userName, string password)
{
try
{
return (_context.Users
.Where(usr => usr.Username == userName && usr.Password == password && usr.Status == "ACTIVE"))
.SingleOrDefault();
}
catch (Exception ex)
{
LogError(ex);
}
return null;
}
Hope you can help me. Thanks a lot!
I've had the same error under slightly different circumstances, I was using inheritance. The problem was fixed by ensuring that all tables/links that can be reached from the model class are configured by your context.
In your case this is the UserAccess and UserAccessDetail classes (and anything else that can be reached from them). Try configuring these in OnModelCreating.
public class Project
{
public virtual int ID { get; set; }
[Required]
public virtual String Title { get; set; }
public String Definition { get; set; }
public DateTime StartDate { get; set; }
[Required]
public int CreaterID { get; set; }
public virtual ICollection<Status> Status { get; set; }
public virtual ICollection<Task> Tasks { get; set; }
public virtual ICollection<User> Users { get; set; }
public Project()
{
Users = new HashSet<User>();
}
}
public class User
{
public int ID { get; set; }
[DisplayName("Kullanıcı Adı")]
[Required]
[MinLength(5, ErrorMessage = "Kullanıcı Adı En Az 5 Karakter Olmalıdır")]
public string username { get; set; }
[DataType(DataType.Password)]
[DisplayName("Şifre")]
[Required]
[MinLength(3,ErrorMessage="Şifre En Az 3 Karakter Olmalıdır")]
public string password { get; set; }
[Required]
public String Name { get; set; }
[Required]
public String Surname { get; set; }
public int? CreaterID { get; set; }
public int level { get; set; }
public ICollection<Task> Tasks { get; set; }
public ICollection<Project> Projects { get; set; }
public User()
{
Projects = new HashSet<Project>();
}
}
public class TaskDB : DbContext
{
public DbSet<Comment> Comments { get; set; }
public DbSet<Project> Projects { get; set; }
public DbSet<Situation> Situaitons { get; set; }
public DbSet<Task> Tasks { get; set; }
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Project>().
HasMany(c => c.Users).
WithMany(p => p.Projects).
Map(
m =>
{
m.MapLeftKey("ProjectId");
m.MapRightKey("UserId");
m.ToTable("ProjectUser");
});
}
}
If I add project , current user added to project users list but project not added current user's projects list
This is my project add code
[HttpPost]
public ActionResult Create(Project proje,Status status)
{
proje.StartDate = DateTime.Now;
proje.Status = new HashSet<Status>();
var user = _db.Users.Single(r=> r.ID == UserRole.ID);
proje.Users.Add(user);
proje.Status.Add(status);
user.Projects.Add(proje);
if (ModelState.IsValid)
{
var projeler = _db.Projects;
projeler.Add(proje);
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(proje);
}
I Search this problem's cause I did not find , I want to learn why entity framework add user to project's list but not add project to user's list
Your code to add the new project to the database looks correct and the relationship is most likely stored.
But possibly you don't load the Projects list with a User. If you call...
var project = _db.Projects.Single(p => p.ID == 1);
var users = project.Users; // lazy loading because Users is virtual
...you will see the project's users because they get lazily loaded since the Project.Users property is marked as virtual. If you do the same with a User...
var user = _db.Users.Single(u => u.ID == 1);
var projects = user.Projects; // no lazy loading because Projects is not virtual
...the projects don't get loaded because the User.Projects property is not marked as virtual.
Either mark the property as virtual as well to enable lazy loading for the User.Projects collection:
public virtual ICollection<Project> Projects { get; set; }
Or use eager loading:
var user = _db.Users.Include(u => u.Projects).Single(u => u.ID == 1);
I am having trouble with Model.IsValid on a property that's not required.
Here's the code.
BeginForm in the Edit.cshtml file
#using (Html.BeginForm("Edit", "Member", FormMethod.Post, new { enctype = "multipart/formdata" }))
{
#Html.Partial("_MemberForm", Model.Member)
}
MemberEditViewModel: (used for the Edit.cshtml file)
public class MemberEditViewModel
{
public MemberFormModel Member { get; set; }
}
MemberFormModel:
public class MemberFormModel : ICreateMemberCommand, IValidatableObject
{
public int Id { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public string SocialSecurityNumber { get; set; }
[Required]
public int PinCode { get; set; }
[Required]
public char Gender { get; set; }
public string Email { get; set; }
[Required]
public string Address { get; set; }
[Required]
public string ZipCode { get; set; }
[Required]
public string ZipAddress { get; set; }
public string Phone { get; set; }
public string Phone2 { get; set; }
[Required]
public string City { get; set; }
[Required]
public int CountryId { get; set; }
//not required (but still displaying error it's required)
public Membership Membership { get; set; }
// not required (displaying error it's required)
public PunchCard PunchCard { get; set; }
public bool IsActive { get; set; }
block of _MemberForm.cshtml (partial)
<fieldset>
<dl>
<dt>#Html.LabelFor(m => m.Id)</dt>
<dd>#Html.TextBoxFor(m => m.Id, new { disabled = "disabled", #readonly = "readonly" })</dd>
<dt>#Html.LabelFor(m => m.PinCode)</dt>
<dd>#Html.EditorFor(m => m.PinCode)</dd>
<!-- problem with membership, maybe with the .FromData/ToDate ? -->
<dt>#Html.LabelFor(m => m.Membership)</dt>
<dd>#Html.EditorFor(m => m.Membership.FromDate, new { #name = "Membership" }) -
#Html.EditorFor(m => m.Membership.ToDate, new { #name="Membership"})</dd>
<!-- problem with punch card, maybe with the .Times ? -->
<dt>#Html.LabelFor(m => m.PunchCard)</dt>
<dd>#Html.EditorFor(m => m.PunchCard.Times, new { #name = "PunchCard" })</dd>
</dl>
</fieldset>
The MemberController Edit Action
// POST: /Members/10002/Edit
[HttpPost]
public ActionResult Edit(FormCollection formValues, MemberFormModel memberForm)
{
var errors = ModelState.Values.SelectMany(v => v.Errors);
if(IsSaveOperation(formValues)){
if(TryUpdateMember(memberForm)){
return RedirectToAction("Details", "Member", new {id = memberForm.Id});
}
}
var mm = new MemberEditViewModel{ Member = memberForm };
return View(mm);
}
Membership.cs
public class Membership
{
public Membership(){ /* empty constructor */}
public Membership(int id, int memberId, DateTime fromDate, DateTime toDate)
{
Id = id;
MemberId = memberId;
FromDate = fromDate;
ToDate = toDate;
}
public int Id { get; set; }
public int MemberId { get; set; }
[DataType(DataType.Date)]
public DateTime FromDate { get; set; }
[DataType(DataType.Date)]
public DateTime ToDate { get; set; }
}
PunchCard.cs
public class PunchCard
{
public PunchCard() { /* empty constructor */ }
public PunchCard(int memberId, int times, DateTime createdDate, DateTime modifiedDate)
{
this.MemberId = memberId;
this.Times = times;
this.CreatedDate = createdDate;
this.ModifiedDate = modifiedDate;
}
public int Id { get; set; }
public int MemberId { get; set; }
public int Times { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime ModifiedDate { get; set; }
}
You see I dont have any [Required] attribute, neither in the MemberFormModel. So how come those two are Required ? Its a mystery.
You should not be using both the disabled and readonly attribute on your textbox:
#Html.TextBoxFor(m => m.Id, new { disabled = "disabled", #readonly = "readonly" })
I guess the disabled attribute takes precedence and the value of the Id is never sent to the server when you submit the form. That's why you get a modelstate error. Because your id property is required. Now you will be probably tell me that it is not decorated with the [Required] attribute but this doesn't matter. Since you have declared it as a non-nullable integer it is implicitly required and the framework automatically makes it required. If you don't want this to happen you should declare it as a nullable integer.
So back to your view, if you want to only display id, without allowing the user to modify it, use readonly:
#Html.TextBoxFor(m => m.Id, new { #readonly = "readonly" })
Obviously don't think that if you made a textbox readonly, the user cannot modify it. The normal user will not. But a hacker could always put whatever value he wants in this textbox and forge a request. So absolutely do not rely on this as some sort of security or something.
I´m started to work with AutoMapper today...
But I´m having some problem with Dropdown model...
What I have so far :
User Model
public class User : Entity
{
public virtual string Name { get; set; }
public virtual string Email { get; set; }
public virtual string Password { get; set; }
public virtual Role Role { get; set; }
}
Role Model
public class Role : Entity
{
public virtual string Name { get; set; }
}
UserUpdateViewModel
public class UserUpdateViewModel
{
public int Id{get;set;}
[Required(ErrorMessage = "Required.")]
public virtual string Name { get; set; }
[Required(ErrorMessage = "Required."), Email(ErrorMessage = "Email Invalid."), Remote("EmailExists", "User", ErrorMessage = "Email already in use.")]
public virtual string Email { get; set; }
[Required(ErrorMessage = "Required.")]
public virtual string Password { get; set; }
[Required(ErrorMessage = "Required")]
public virtual string ConfirmPassword { get; set; }
[Required(ErrorMessage = "Required.")]
public int RoleId { get; set; }
public IList<Role> Roles { get; set; }
}
UserController
public ActionResult Update(int id=-1)
{
var _user = (_userRepository.Get(id));
if (_user == null)
return RedirectToAction("Index");
Mapper.CreateMap<User, UserUpdateViewModel>();
var viewModel = Mapper.Map<User, UserUpdateViewModel>(_user);
viewModel.Roles = _roleRepository.GetAll();
return View(viewModel);
}
[HttpPost, Transaction]
public ActionResult Update(UserViewModel user)
{
if (ModelState.IsValid)
{
user.Password = _userService.GetPasswordHash(user.Password);
Mapper.CreateMap<UserViewModel, User>();
var model = Mapper.Map<UserViewModel, User>(user); //model.Role = null
_userRepository.SaveOrUpdate(model); //ERROR, because model.Role = null
return Content("Ok");
}
return Content("Erro").
}
View Update
...
#Html.DropDownListFor(model => model.RoleId, new SelectList(Model.Roles, "Id", "Name"), "-- Select--", new { #class = "form radius" })
...
Some considerations:
1 - I´m returning Content() because is all Ajax enabled using HTML 5 PushState etc etc
2 - In my Update(POST one) method, my model returned by Autommapper has Role = null
Why my Role returned by Automapper is null?
Is that the right way to work with AutoMapper? Any tip?
Thanks
The map is failing because you are trying to map a single Role directly to a collection of Roles. And a collection of Roles back to a single Role. You cant directly map between these as they are different types.
If you wanted to map a Role to a List then you could use a custom value resolver.
Mapper.CreateMap<User , UserUpdateViewModel>()
.ForMember(dest => dest.Roles, opt => opt.ResolveUsing<RoleToCollectionResolver>())
Public class RoleToCollectionResolver: ValueResolver<User,IList<Role>>{
Protected override IList<Role> ResolveCore(User source){
var roleList = new List<Role>();
roleList.Add(source.Role);
Return roleList;
}
}