EF Core Fluent API statement as Data Annotation - api

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");
});

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; }
}

.NET CORE 3.1 DATABASE FÄ°RST How to access the name of Id received with foreign key

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

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;

Nhibernate Mapping relationships on multiple columns

I'm having problems mapping a relationaship between two entities when there are two columns involved in the mapping.
I'm modelling a state machine with two object types - State and Transition. Each process has its own state machine, so States and Transitions need to be identified by ProcessId. My entity classes are like this:
public class State
{
public virtual long Id { get; set; }
public virtual int ProcessId { get; set; }
public virtual int Ordinal { get; set; }
public virtual Process Process { get; set; }
public virtual ICollection<Transition> TransitionsIn { get; set; }
public virtual ICollection<Transition> TransitionsOut { get; set; }
}
public class Transition
{
public virtual long Id { get; set; }
public virtual long ProcessId { get; set; }
public virtual int FromStateNum { get; set; }
public virtual int ToStateNum { get; set; }
public virtual long StateActionId { get; set; }
public virtual Process Process { get; set; }
public virtual StateAction StateAction { get; set; }
public virtual State FromState { get; set; }
public virtual State ToState { get; set; }
}
I need the navigation properties (State.TransitionsIn, State.TransitionsOut, Transition.FromState, Transition.ToState) to be based on the ProcessId and the Ordinal number of the state. For example, Transition.FromState should navigate to the entity where t.ProcessId = s.ProcessId and t.FromStateNum = s.Ordinal.
I've tried the following mapping, but it complains that I'm using two columns to map to one (StateId).
public class StateMap : ClassMap<State>
{
public StateMap()
{
Id(x => x.Id);
HasMany(s => s.TransitionsIn)
.KeyColumns.Add("ProcessId", "ToStateNum")
.Inverse();
HasMany(s => s.TransitionsOut)
.KeyColumns.Add("ProcessId", "FromStateNum")
.Inverse();
}
}
public class TransitionMap : ClassMap<Transition>
{
public TransitionMap()
{
Id(x => x.Id);
References(t => t.FromState)
.Columns("ProcessId", "Ordinal");
References(t => t.ToState)
.Columns("ProcessId", "Ordinal");
}
}
How can I get this to work?
How about this mapping.. I have not tested it but just trying to give a direction.
public class StateMap : ClassMap<State>
{
public StateMap()
{
Id(x => x.Id);
HasMany(s => s.TransitionsIn)
.KeyColumn("ProcessId")
.KeyColumn("ToStateNum").PropertyRef("Ordinal")
.Inverse();
HasMany(s => s.TransitionsOut)
.KeyColumn("ProcessId")
.KeyColumn("FromStateNum").PropertyRef("Ordinal")
.Inverse();
}
}
public class TransitionMap : ClassMap<Transition>
{
public TransitionMap()
{
Id(x => x.Id);
References(t => t.FromState)
.Columns("ProcessId", "FromStateNum");
References(t => t.ToState)
.Columns("ProcessId", "ToStateNum");
}
}