.net identityuser problems with entityframework - entity-framework

When we start a normal MVC project it comes with Identity.I have some models like Post.cs and Comment.cs
One to many relationship between post and comment
public class Post
{
public int PostId { get; set; }
public string Baslik { get; set; }
public string Icerik { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
}
public class Comment
{
public int CommentId { get; set; }
public string Icerik { get; set; }
public int PostId {get;set;}
public virtual Post Post { get; set; }
}
IdentityModel.cs We have nothing in here but when i click with ctrl on IdentityUser
public class ApplicationUser : IdentityUser
{
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
}
public class IdentityUser : IUser
{
public IdentityUser();
public IdentityUser(string userName);
public virtual ICollection<IdentityUserClaim> Claims { get; }
public virtual string Id { get; set; }
public virtual ICollection<IdentityUserLogin> Logins { get; }
public virtual string PasswordHash { get; set; }
public virtual ICollection<IdentityUserRole> Roles { get; }
public virtual string SecurityStamp { get; set; }
public virtual string UserName { get; set; }
}
Still weird to me for realationship and i clicked with ctrl on IUser
// Summary:
// Minimal interface for a user with a string user key
public interface IUser
{
// Summary:
// Unique key for the user
//
// Returns:
// The unique key for the user
string Id { get; }
string UserName { get; set; }
}
What am I missing? I just want a relationship user-comment and user-post like between Post and Comment models.

Related

EFCore- Save Entity with child entity records

Here are my models:
public partial class UserDTO
{
public int UserId { get; set; }
public ICollection<Userskills> Userskills { get; set; }
}
public partial class SkillsmasterDTO
{
public sbyte SkillId { get; set; }
public string Skill { get; set; }
public ICollection<Userskills> Userskills { get; set; }
}
public partial class UserskillsDTO
{
public int UserId { get; set; }
public sbyte SkillId { get; set; }
public SkillsmasterDTO Skill { get; set; }
public UsermasterDTO User { get; set; }
}
public class UserMaster
{
public int UserId { get; set; }
public List<UserSkills> UserSkills{get;set;}
//other fields
}
public class SkillsMaster
{
public sbyte SkillId { get; set; }
public string Skill { get; set; }
}
public class UserSkills
{
public int UserId { get; set; }
public sbyte SkillId { get; set; }
public string Skill { get; set; }
}
I want to save UserMaster, and along with that I want to save UserSkills also.
I am sending data in following format:
{"FirstName": "Priya",
"LastName": "Dave",
"Email":"priya.dave#xyz.com",
"Password":"123456",
"ContactNo":"1234",
"RoleId":1,
"CreatedBy":15,
"UserTypeId":2,
"LocationId":1,
"BandId":1,
"PostId":1,
"IsActive":1,
"UserSkills":[{"SkillId":1}]
}
Code I've written for save is:
var insertedEmployee= unitOfWork.UserRepository.Add(Mapper.Map<Usermaster>(employee));
_unitOfWork.Save();
It is saving user details but UserSkills is not getting saved. How can I do that? I went through some blogs but not able to find proper solution.
Because UserSkills is persisted in a different table than UserMaster, you need to do the following for a unit of work.
Add UserMaster to context.UserMasters table
Add UserSkills to context.UserSkills table
Add UserSkills to context.UserMaster object
Then context.SaveChanges()

EF Code First Multiplicity

I've got the following :
public class ApplicationUser : IdentityUser
{
public ApplicationUser()
{
}
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
[ForeignKey("UserProfile")]
public int UserProfileID { get; set; }
public UserProfile UserProfile { get; set; }
}
}
public class UserProfile : BaseModel
{
[Key]
public int UserProfileID { get; set; }
[Required]
public String FirstName { get; set; }
[Required]
public String LastName { get; set; }
public String LicenseNumber { get; set; }
public String Position { get; set; }
public bool? Active { get; set; }
[Required]
[ForeignKey("ApplicationUser")]
public String AppUserID { get; set; }
public ApplicationUser ApplicationUser { get; set; }
[ForeignKey("Division")]
public int? DivisionID { get; set; }
public virtual Division Division { get; set; }
public virtual ICollection<Building> Buildings { get; set; }
public virtual ICollection<UserProcess> UserProcesses { get; set; }
public UserProfile()
{
Buildings = new HashSet<Building>();
}
}
I'm getting the error
'UserProfile_ApplicationUser_Target: : Multiplicity is not valid in
Role 'UserProfile_ApplicationUser_Target' in relationship
'UserProfile_ApplicationUser'. Because the Dependent Role properties
are not the key properties, the upper bound of the multiplicity of the
Dependent Role must be '*'."
I don't see what's wrong. This should be a 1:1 relationship. An ApplicationUser has a userProfile and UserProfile always has an applicationuser. Is the way I have it coded making it a 1 to many relationship since multiple user profiles could have an ApplicationUser? I want to maintain the int key on UserProfile.

EF 6 Code First Mapping one-to-many

Can someone please help me with mapping the following hierarchy with EF 6 code first? I can find anything useful for the below example in the documentation.
namespace Contacts {
public class Person
{
public Person()
{
this.Emails = new HashSet<Email>();
}
public long Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<Email> Emails { get; set; }
}
public class Company
{
public Company()
{
this.Emails = new HashSet<Email>();
}
public long Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Email> Emails { get; set; }
}
public class Email
{
public string Value { get; set; }
public string Label { get; set; }
public string TargetId { get; set; }
public string TargetType { get; set; }
}
}
TargetType can be set to Company or Person depending on the entity that contains the Email instance.
DB Schema:

EF6 generates all the entity classes (tt .cs) in single file (eg. model.cs) and not as separate .cs file

I am using EF6. I have 2 tables Events and Users for which I used database first approach to generate the EDMX models and entity classes. Everything works fine but the entity classes are coming under a single file in this case EventSample.cs(shown below). I am not getting separate files for each entity as Event.cs and User.cs. Please let me know if this is correct and if not how to rectify it?
public partial class Event
{
public Event()
{
this.Users = new HashSet<User>();
}
public int Id { get; set; }
public string Title { get; set; }
public System.DateTime Time { get; set; }
public string Location { get; set; }
public string Description { get; set; }
public int Creator_Id { get; set; }
public virtual User User { get; set; }
public virtual ICollection<User> Users { get; set; }
}
public partial class User
{
public User()
{
this.Events = new HashSet<Event>();
this.Events1 = new HashSet<Event>();
}
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public virtual ICollection<Event> Events { get; set; }
public virtual ICollection<Event> Events1 { get; set; }
}

One to many relation with cascade giving error

I am learning EF Code First with migrations, I have 3 entities :
[User] 1--->* [Call] 1--->* [ETA]
Code :
User.cs
public class User
{
[Key]
public int Id { get; set; }
public Guid LongId { get; set; }
[Required]
public string Name { get; set; }
public virtual ICollection<Call> Calls { get; set; } // many calls
public User()
{
LongId = Guid.NewGuid();
}
}
Call.cs
public class Call
{
[Key]
public int Id { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string BreakdownNo { get; private set; }
[Required,MaxLength(32)]
public string Customer { get; set; }
[Required,MaxLength(32)]
public string TrailerNo { get; set; }
[Required, MaxLength(32)]
public string DepotContact { get; set; }
[Required, MaxLength(48), RegularExpression(#"^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$")]
public string DepotEmail { get; set; }
[Required, MinLength(9), MaxLength(32)]
public string DepotPhone { get; set; }
[Required, MaxLength(32)]
public string DriverContact { get; set; }
[Required, MinLength(9), MaxLength(32), RegularExpression(#"^(7\d{3}|\(?07\d{3}\)?)\s?\d{3}\s?\d{3}$")]
public string DriverPhone { get; set; }
[Required, MaxLength(256)]
public string LocatedAtFreeText { get; set; }
[Required, MaxLength(8), RegularExpression(#"^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {0,1}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$")]
public string LocatedAtPostCode { get; set; }
[Required, MaxLength(16)]
public string StartupNo { get; set; }
[Required]
public bool IsLoaded { get; set; }
[Required, MaxLength(256)]
public string FaultDescription { get; set; }
[Required]
public DateTime StartTime { get; set; }
public DateTime? EndTime { get; set; }
public string Status { get; set; }
public virtual User Controller { get; set; } // 1 controller
public virtual ICollection<ETA> ETAs { get; set; } // many ETAs
public Call()
{
StartTime = DateTime.Now;
ETAs = new List<ETA> { new ETA() };
Status = "Logged";
}
}
ETA.c
public class ETA
{
[Key]
public int Id { get; set; }
[Required]
public TimeSpan Value { get; set; }
public int CallId { get; set; }
public ETA()
{
Value = TimeSpan.FromMinutes(90);
}
}
I would like it so when I delete the User it deletes all of the Calls for the User, which in turn deletes all of the ETAs for those Calls.
When I delete a User row from the Database (using database explorer) it gives me an error :
No rows were deleted.
A problem occurred attempting to delete row 201.
Error Source: .Net SqlClient Data Provider.
Error Message: The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.Calls_dbo.Users_Controller_Id". The conflict occurred in database "BreakdownDb", table "dbo.Calls", column 'Controller_Id'.
You can turn on the Cascade Delete option in Entity Framework, here you will find more info:
http://blogs.msdn.com/b/alexj/archive/2009/08/19/tip-33-how-cascade-delete-really-works-in-ef.aspx
The solution was to add OnModelCreating method to my DbContext class :
public class BreakdownDb : DbContext
{
public DbSet<Call> Calls { get; set; }
public DbSet<User> Users { get; set; }
public BreakdownDb(): base("name=DefaultConnection") {}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().HasMany(x => x.Calls).WithRequired();
modelBuilder.Entity<Call>().HasMany(x => x.ETAs).WithRequired();
}
}