.NET CORE 3.1 DATABASE FİRST How to access the name of Id received with foreign key - asp.net-core

I'm working on a project using database first with .NET core 3.1 .When I access the column information of the ID received with the Foreign key, it is null.
User Model
public partial class User
{
public User()
{
Article = new HashSet<Article>();
}
[Key]
public int UserId { get; set; }
[StringLength(50)]
public string UserName { get; set; }
[StringLength(50)]
public string UserSurname { get; set; }
[StringLength(50)]
public string Password { get; set; }
[StringLength(50)]
public string UserEmail { get; set; }
public int? RolId { get; set; }
[ForeignKey(nameof(RolId))]
[InverseProperty(nameof(Role.User))]
public virtual Role Rol { get; set; }
[InverseProperty("User")]
public virtual ICollection<Article> Article { get; set; }
}
}
Role Model
public partial class Role
{
public Role()
{
User = new HashSet<User>();
}
[Key]
public int RoleId { get; set; }
[StringLength(50)]
public string RoleName { get; set; }
[InverseProperty("Rol")]
public virtual ICollection<User> User { get; set; }
}
}
AdventureContext
public partial class AdventureContext : DbContext
{
public AdventureContext()
{
}
public AdventureContext(DbContextOptions<AdventureContext> options)
: base(options)
{
}
public virtual DbSet<Article> Article { get; set; }
public virtual DbSet<Category> Category { get; set; }
public virtual DbSet<Comment> Comment { get; set; }
public virtual DbSet<Images> Images { get; set; }
public virtual DbSet<Role> Role { get; set; }
public virtual DbSet<User> User { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("Server=DESKTOP-Q779BF0\\SQLEXPRESS;Database=cmsData;Trusted_Connection=True;");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Article>(entity =>
{
entity.HasOne(d => d.Category)
.WithMany(p => p.Article)
.HasForeignKey(d => d.CategoryId)
.HasConstraintName("FK_Article_Category");
entity.HasOne(d => d.Image)
.WithMany(p => p.Article)
.HasForeignKey(d => d.ImageId)
.HasConstraintName("FK_Article_Images");
entity.HasOne(d => d.User)
.WithMany(p => p.Article)
.HasForeignKey(d => d.UserId)
.HasConstraintName("FK_Article_User");
});
modelBuilder.Entity<Comment>(entity =>
{
entity.HasOne(d => d.Article)
.WithMany(p => p.Comment)
.HasForeignKey(d => d.ArticleId)
.HasConstraintName("FK_Comment_Article");
});
modelBuilder.Entity<User>(entity =>
{
entity.HasOne(d => d.Rol)
.WithMany(p => p.User)
.HasForeignKey(d => d.RolId)
.HasConstraintName("FK_User_Role");
});
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
}
View
#foreach (var item in Model)
{
#Html.DisplayFor(modelItem => item.UserName)
#Html.DisplayFor(modelItem => item.UserSurname)
#Html.DisplayFor(modelItem => item.Password)
#Html.DisplayFor(modelItem => item.UserEmail)
#Html.DisplayFor(modelItem => item.Rol.RoleName)
}
I want to get rolename. Why not coming ?
[UserIndex List View][1]
[1]: https://i.stack.imgur.com/2f2CZ.png

You should load the related entities in your controller action method. Something like this:
var list = db.User.Include(u => u.Rol).ToList();
You can read more about how to load related entities in the Microsoft Docs: https://learn.microsoft.com/en-us/ef/core/querying/related-data

Related

Fluent NHibernate Mapping multiple tables has relation and joined to each other

As you see the models have references as one to many. list of project is not mapped here. there are more than one project and the project has more than one role and the role has more than one permission.
error is persister system not avialable.
can anyone look up and help me ?
public class Permission
{
public virtual int MId { get; set; }
public virtual string Id { get; set; }
public virtual bool View { get; set; }
public virtual bool Add { get; set; }
public virtual bool Edit { get; set; }
public virtual bool Delete { get; set; }
public virtual Role Roles { get; set; }
}
public class Role
{
public virtual int RId { get; set; }
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual string Site_Id { get; set; }
public virtual string Site_Name { get; set; }
public virtual string Domain { get; set; }
public virtual List<Permission> permissions { get; set; }
public virtual Project Project { get; set; }
}
public class Project
{
public virtual int PId { get; set; }
public virtual string Id { get; set; }
public virtual string Name { get; set; }
public virtual List<Role> Roles { get; set; }
}
Mappings
public class PermissionMapping : ClassMap<Permission>
{
public PermissionMapping()
{
Table("ModulePermissions");
Id(u => u.MId).GeneratedBy.Identity();
Map(u => u.Id).Column("ModuleName");
Map(u => u.View);
Map(u => u.Edit);
Map(u => u.Add);
Map(u => u.Delete);
References(x => x.Roles).Column("RolePermissionId");
}
}
public class RoleMapping : ClassMap<Role>
{
public RoleMapping()
{
Table("ModuleRole");
Id(u => u.RId).GeneratedBy.Identity();
Map(u => u.Name);
Map(u => u.Site_Id).Column("SiteId");
Map(u => u.Site_Name).Column("SiteName");
Map(u => u.Domain);
References(x => x.Project).Column("RoleProjectId");
HasMany(u => u.permissions).KeyColumn("RolePermissionId").Inverse().Cascade.All().Not.LazyLoad();
}
}
public class ProjectsMapping : ClassMap<Project>
{
public ProjectsMapping()
{
Table("Projects");
Id(u => u.PId).GeneratedBy.Identity();
Map(u => u.Id).Column("ApiProjectId");
Map(u => u.Name);
HasMany(u => u.Roles).KeyColumn("RoleProjectId").Inverse().Cascade.All().Not.LazyLoad();
}
}

Invalid Column name when adding Migration

I am using .NET 5 and getting this error when I try to add a column to my database. The only fixes I found so far was to set the right startup project, but since I dont have two projects I dont know how to fix it.
An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: Invalid column name 'EspStartTime'.
Unable to create an object of type 'ApplicationDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
ApplicationDbContext
internal class TaskEntityTypeConfiguration : IEntityTypeConfiguration<Task>
{
public void Configure(EntityTypeBuilder<Task> builder)
{
builder.Property(e => e.Description)
.HasConversion(
xml => xml.ToString(),
xml => xml != null ? XElement.Parse(xml) : null)
.HasColumnType("xml");
}
}
internal class StudentAssignedTaskEntityTypeConfiguration : IEntityTypeConfiguration<StudentAssignment>
{
public void Configure(EntityTypeBuilder<StudentAssignment> builder)
{
builder.Property(e => e.FeedbackXml)
.HasConversion(
xml => xml.ToString(),
xml => xml != null ? XElement.Parse(xml) : null)
.HasColumnType("xml");
builder.Property(e => e.StudentSubmissionAttachmentsXml)
.HasConversion(
xml => xml.ToString(),
xml => xml != null ? XElement.Parse(xml) : null)
.HasColumnType("xml");
builder.Property(e => e.StudentSubmissionXml)
.HasConversion(
xml => xml.ToString(),
xml => xml != null ? XElement.Parse(xml) : null)
.HasColumnType("xml");
}
}
public class ApplicationDbContext : IdentityApplicationDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
//this.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
}
public static readonly ILoggerFactory Factory
= LoggerFactory.Create(builder => { builder.AddConsole(); });
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
optionsBuilder.UseLoggerFactory(Factory);
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
foreach (var relationship in builder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
relationship.DeleteBehavior = DeleteBehavior.Restrict;
builder.Entity<ApplicationUser>().HasMany(x => x.TeacherGroups).WithOne(x => x.Teacher).OnDelete(DeleteBehavior.SetNull);
builder.Entity<ApplicationUser>().HasMany(x => x.StudentGroups).WithMany(x => x.Students);
builder.Entity<SchoolClassStudentTerm>().HasKey(x => new { x.StudentId, x.SchoolClassId, x.TermId });
builder.ApplyConfiguration(new TaskEntityTypeConfiguration());
builder.ApplyConfiguration(new StudentAssignedTaskEntityTypeConfiguration());
builder.Entity<GroupAssignment>().HasOne(x => x.ClassroomGroup).WithMany(x => x.GroupAssignments).OnDelete(DeleteBehavior.Cascade);
builder.Entity<GroupAssignment>().HasMany(x => x.StudentAssignments).WithOne(x => x.GroupAssignment).OnDelete(DeleteBehavior.Cascade);
builder.Entity<GroupAssignment>().HasOne(x => x.Task).WithMany(x => x.GroupAssignments).OnDelete(DeleteBehavior.Cascade);
builder.Entity<SchoolClassStudentTerm>().HasOne(x => x.Student).WithMany(x => x.SchoolClassStudentTerms).OnDelete(DeleteBehavior.Cascade);
builder.Entity<StudentAssignment>().HasOne(x => x.Student).WithMany().OnDelete(DeleteBehavior.SetNull);
builder.Entity<GroupAssignment>().HasOne(x => x.Creator).WithMany(x => x.CreatedGroupAssignments).OnDelete(DeleteBehavior.SetNull);
builder.Entity<SchoolClass>().HasMany(x => x.SchoolClassStudentTerms).WithOne(x => x.SchoolClass);
// see https://learn.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x?view=aspnetcore-5.0#add-identityuser-poco-navigation-properties
builder.Entity<ApplicationUser>().HasMany(x => x.UserRoles).WithOne(x => x.User)
.HasForeignKey(x => x.UserId).IsRequired().OnDelete(DeleteBehavior.Cascade);
}
public DbSet<SchoolClassStudentTerm> SchoolClassStudentTerms { get; set; }
public DbSet<Term> Terms { get; set; }
public DbSet<StudentAssignment> StudentAssignments { get; set; }
public DbSet<ClassroomGroup> ClassroomsGroups { get; set; }
public DbSet<SchoolClass> SchoolClasses { get; set; }
public DbSet<GroupAssignment> GroupAssignments { get; set; }
public DbSet<Task> Tasks { get; set; }
public DbSet<Subject> Subjects { get; set; }
IdentityDbContext
// see https://learn.microsoft.com/en-us/aspnet/core/security/authentication/customize-identity-model?view=aspnetcore-5.0
public abstract class IdentityApplicationDbContext : IdentityDbContext<
ApplicationUser, ApplicationRole, string,
IdentityUserClaim<string>, ApplicationUserRole, IdentityUserLogin<string>,
IdentityRoleClaim<string>, IdentityUserToken<string>>
{
public IdentityApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ApplicationUser>(b =>
{
// Each User can have many entries in the UserRole join table
b.HasMany(e => e.UserRoles)
.WithOne(e => e.User)
.HasForeignKey(ur => ur.UserId)
.IsRequired();
});
modelBuilder.Entity<ApplicationRole>(b =>
{
// Each Role can have many entries in the UserRole join table
b.HasMany(e => e.UserRoles)
.WithOne(e => e.Role)
.HasForeignKey(ur => ur.RoleId)
.IsRequired();
});
}
}
ApplicationUser
public class ApplicationUser : IdentityUser
{
public virtual ICollection<ApplicationUserRole> UserRoles { get; set; }
public virtual ICollection<ClassroomGroup> TeacherGroups { get; set; }
public virtual ICollection<ClassroomGroup> StudentGroups { get; set; }
public virtual ICollection<Task> CreatedTasks { get; set; }
public virtual ICollection<SchoolClassStudentTerm> SchoolClassStudentTerms { get; set; }
public virtual ICollection<GroupAssignment> CreatedGroupAssignments { get; set; }
public bool Disabled { get; set; }
public String FullName { get; set; }
public DateTime? EspStartTime { get; set; }
}
ClassroomGroup
public class ClassroomGroup
{
public int SubjectId { get; set; }
public virtual Subject Subject { get; set; }
public virtual SchoolClass SchoolClass { get; set; }
public int SchoolClassId { get; set; }
public String TeacherId { get; set; }
public virtual ApplicationUser Teacher { get; set; }
public int Id { get; set; }
public String Title { get; set; }
public virtual ICollection<ApplicationUser> Students { get; set; }
public int TermId { get; set; }
public virtual Term Term { get; set; }
public virtual ICollection<GroupAssignment> GroupAssignments { get; set; }
}

EF Core Fluent API statement as Data Annotation

Can I write this with data annotations in EF Core?
modelBuilder.Entity<DiagramComponent>()
.HasOne(c => c.Compressor)
.WithMany(c => c.Components);
You will have to create one more class:
public class DiagramComponentComponent
{
public int DiagramComponentId { get; set; }
public int ComponentId { get; set; }
[ForeignKey(nameof(DiagramComponentId))]
public virtual DiagramComponent DiagramComponent { get; set; }
[ForeignKey(nameof(ComponentId))]
public virtual Component Component { get; set; }
}
and add attributes to existing classes:
public class DiagramComponent
{
public int CompressorId { get; set; }
[ForeignKey(nameof(CompressorId))]
[InverseProperty("DiagramComponents")]
public virtual Compressor Compressor { get; set; }
[InverseProperty(nameof(DiagramComponentComponent.DiagramComponent))]
public virtual ICollection<DiagramComponentComponent> DiagramComponentComponents { get; set; }
}
public class Compressor
{
[InverseProperty(nameof(DiagramComponent.Compressor))]
public virtual ICollection<DiagramComponent> DiagramComponents { get; set; }
}
public class Component
{
[InverseProperty(nameof(DiagramComponentComponent.Component))]
public virtual ICollection<DiagramComponentComponent> DiagramComponentComponents { get; set; }
}
and add to dbcontext:
modelBuilder.Entity<DiagramComponentComponent>(entity =>
{
entity.HasOne(d => d.DiagramComponent )
.WithMany()
.HasForeignKey(d => d.DiagramComponentId )
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_DiagramComponentComponent_Component_Diagram");
entity.HasOne(d => d.Component)
.WithMany()
.HasForeignKey(d => d.ComponentId )
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_DiagramComponentComponent_Component");
});

FluentNhibernate and HasMany

I try a simple Test Application with FluentNhibernate but it doesnt work as I expected.
Here are my classes:
public class Document : DataEntity
{
public virtual string Title { get; set; }
public virtual string FileName { get; set; }
public virtual DateTime LastModificationDate { get; set; }
public virtual User LastModificationBy { get; set; }
public virtual byte[] Content { get; set; }
public virtual User Owner { get; set; }
}
public class User : DataEntity
{
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
public virtual string Login { get; set; }
public virtual string PasswordHash { get; set; }
public virtual string Email { get; set; }
public virtual IList<Document> OwnedDocuments { get; set; }
public User()
{
this.OwnedDocuments = new List<Document>();
}
}
internal class UserMapping : ClassMap<User>
{
public UserMapping()
{
this.Id(x => x.Id);
this.Map(x => x.FirstName);
this.Map(x => x.LastName);
this.HasMany(x => x.OwnedDocuments).Inverse();
}
}
public DocumentMapping()
{
this.Id(x => x.Id);
this.Map(x => x.Title);
this.Map(x => x.FileName).Not.Nullable();
this.Map(x => x.LastModificationDate).Index("IDX_ModificationDate");
this.Map(x => x.Content);
this.References(x => x.LastModificationBy).Column("LastModificationBy");
this.References(x => x.Owner).Column("Owner");
this.Table("Document");
}
I try to test it with the following code
using (var transaction = Session.BeginTransaction())
{
var users = this.kernel.Get<IRepository<User>>();
var document = this.kernel.Get<IRepository<Document>>();
var user = new User { Login = "Blubb" };
users.Add(user);
var list = Builder<Document>.CreateListOfSize(50).All().With(x => x.Owner = user).Build().ToList();
var list2 = Builder<Document>.CreateListOfSize(50).All().Build().ToList();
list.ForEach(x => user.OwnedDocuments.Add(x));
document.Add(list);
document.Add(list2);
transaction.Commit();
var i = document.All().Count();
i.Should().Be(50);
var docs = ((IGuidKeyedRepository<User>)users).FindBy(user.Id).OwnedDocuments.Count();
docs.Should().Be(50);
}
The first problem is, why is the document count always 0 when I dont call document.Add(list);? I thought when I add some documents to the document collection of the user, they will be automaticly added to the documents?
And why ist the last test 100? Because I filter on the documents belongs to that user.
It looks like you need to set a cascade option on the child collection OwnedDocuments
this.HasMany(x => x.OwnedDocuments).Inverse().Cascade.AllDeleteOrphan();
The setting above will save all the children if you add any to the collection and if you remove them from the collection and save the object it will delete those child objects. You can find out more information about these settings in the nhibernate documentation:
http://www.nhforge.org/doc/nh/en/

Delete on Many to Many Relationship using Fluent Nhibernate

User Class
public class User
{
public virtual Guid UserID { get; set; }
public virtual string UserName { get; set; }
public virtual string Password { get; set; }
public virtual string FullName { get; set; }
public virtual string Email { get; set; }
public virtual TimeSpan LastLogin { get; set; }
public virtual bool IsActive { get; set; }
public virtual DateTime CreationDate { get; set; }
public virtual IList<Role> Roles { get; set; }
public User()
{
Roles = new List<Role>();
}
public virtual void AddRoles(Role role)
{
role.Users.Add(this);
Roles.Add(role);
}
}
Role Class
public class Role
{
public virtual int? RoleID { get; set; }
public virtual string RoleName { get; set; }
public virtual bool IsActive { get; set; }
public virtual string Description { get; set; }
public virtual IList<User> Users { get; set; }
public virtual IList<Role> Roles { get; set; }
public Role()
{
Users = new List<User>();
}
}
UserMap Class
public class UserMap : ClassMap<User>
{
public UserMap()
{
Table("tblUsers");
Id(user => user.UserID).GeneratedBy.Guid();
Map(user => user.UserName).Not.Nullable();
Map(user => user.Password).Not.Nullable();
Map(user => user.FullName).Not.Nullable();
Map(user => user.Email).Not.Nullable();
//Map(user => user.LastLogin).Nullable();
Map(user => user.IsActive).Not.Nullable();
Map(user => user.CreationDate).Not.Nullable();
HasManyToMany<Role>(x => x.Roles).Table("tblUserInRoles")
.ParentKeyColumn("UserID")
.ChildKeyColumn("RoleID")
.Cascade.All()
//.AsSet()
//.Inverse()
.Not.LazyLoad();
}
}
RoleMap Class
public class RoleMap : ClassMap<Role>
{
public RoleMap()
{
Table("tblRoles");
Id(role => role.RoleID).GeneratedBy.Identity();
Map(role => role.RoleName).Not.Nullable();
Map(role => role.IsActive).Not.Nullable();
Map(role => role.Description).Not.Nullable();
HasManyToMany<User>(x => x.Users)
.Table("tblUserInRoles")
.ParentKeyColumn("RoleID")
.ChildKeyColumn("UserID")
.Cascade.All()
.Inverse()
.Not.LazyLoad();
}
}
My questions are:
I want to delete all roles of particular user? [Answered by danyolgiax]
Get roles of user
Can Any one guide me..
try .Inverse() on User (not on Role) and then:
user.Roles.Clear();
yourNhSession.SaveOrUpdate(user);
update
User user= yourNhSession.Get<User>(userId);
IList<Role> role= user.Roles;