System Details
FluentValidation version: FluentValidation, Version=7.0.0.0
Web Framework version :ASP.NET Core 2.1
Issue Description
public class Address
{
public string Address { get; set; }
public string City { get; set; }
}
public class AddressValidator : AbstractValidator<Address>
{
public AddressValidator()
{
RuleFor(x => x.Address).NotEmpty().WithMessage("The Address cannot be empty.");
RuleFor(x => x.City).NotEmpty().WithMessage("The City cannot be empty.");
}
}
public class PersonBase
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Address PermanentAddress { get; set; }
}
public class PersonGroupA : PersonBase
{
public int TotalSaleCount { get; set; }
}
public class PersonGroupB : PersonBase
{
public int TodaySaleCount { get; set; }
}
public class PersonBaseValidator : AbstractValidator<PersonBase>
{
public PersonBaseValidator()
{
RuleFor(x => x.FirstName).NotEmpty().WithMessage("The First Name cannot be empty.");
RuleFor(x => x.LastName).NotEmpty().WithMessage("The Last Name cannot be empty.");
RuleFor(x => x.PermanentAddress).SetValidator(new AddressValidator());
}
}
public class PersonGroupAValidator : AbstractValidator<PersonGroupA>
{
public PersonGroupAValidator()
{
RuleFor(x => x.TotalSaleCount).NotEmpty().WithMessage("The Total Sale Count cannot be empty.");
}
}
public class PersonGroupBValidator : AbstractValidator<PersonGroupB>
{
public PersonGroupBValidator()
{
RuleFor(x => x.TodaySaleCount).NotEmpty().WithMessage("The Today Sale Count cannot be empty.");
}
}
how to use base validator in child validator
This is working when add likebelow
public class PersonGroupAValidator : AbstractValidator<PersonGroupA> {
public PersonGroupAValidator() {
Include(new PersonBaseValidator());
RuleFor(x => x.TotalSaleCount).NotEmpty().WithMessage("The Total Sale Count cannot be empty.");
}
}
Related
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; }
}
I have two classes, each having a domain and a repo version.
DOMAIN:
public class MusicInfo
{
public string Id { get; set; }
public MusicImage Image { get; set; }
public MusicInfo(byte[] image)
{
this.Image = new MusicImage(this, image);
}
}
public class MusicImage
{
public byte[] Blob { get; set; }
public MusicInfo MusicInfo { get; set; }
public string Id { get; set; }
public MusicImage(MusicInfo musicInfo, byte[] blob)
{
if (musicInfo == null)
throw new ArgumentNullException("musicInfo");
if (blob == null)
throw new ArgumentNullException("blob");
this.MusicInfo = musiscInfo;
this.Blob = blob;
}
}
REPO:
public class MusicInfoRepo
{
public virtual long Id { get; set; }
public virtual MusicImageRepo Image { get; set; }
}
public class MusicImageRepo
{
public virtual byte[] Blob { get; set; }
public virtual MusicInfoRepo MusicInfo { get; set; }
public virtual long Id { get; set; }
}
And here are their mappings:
public class MusicInfoRepoMap : HighLowClassMapping<MusicInfoRepo>
{
public MusicInfoRepoMap()
{
Table("MusicInfo");
Id(f => f.Id, m => m.Generator(Generators.HighLow, HighLowMapper));
OneToOne(f => f.Image, m => m.Cascade(Cascade.All));
}
}
public class MusicImageRepoMap : ClassMapping<MusicImageRepo>
{
public MusicImageRepoMap()
{
Table("MusicImage");
Id(f => f.Id, m => m.Generator(Generators.Foreign<MusicImageRepo>(f => f.MusicInfo)));
Property(f => f.Blob, m =>
{
m.NotNullable(true);
m.Column(c => c.SqlType("VARBINARY(MAX)"));
m.Length(Int32.MaxValue);
m.Update(false);
});
OneToOne(f => f.MusicInfo,
m =>
{
m.Cascade(Cascade.None);
m.Constrained(true);
m.Lazy(LazyRelation.NoLazy);
});
}
}
When I am trying to query for a ClassA that has a one to one relationship with ClassB which also has a one to one relationship with MusicInfo, an error occurs that says:
Missing type map configuration or unsupported mapping.
Mapping types:
MusicImageRepo -> Byte[]
Blah.MusicImageRepo -> System.Byte[]
Destination path:
List`1[0]
Source value:
Blah.MusicImageRepo
but here is how i map them:
Mapper.CreateMap<MusicInfo, MusicInfoRepo>();
Mapper.CreateMap<MusicInfoRepo, MusicInfo>();
Mapper.CreateMap<MusicImage, MusicImageRepo>();
Mapper.CreateMap<MusicImageRepo, MusicImage>();
There are no problems when saving these classes.
I really dont get why the error happens.
Will really appreciate your help.
OneToOne says that the other entity/table has the Reference(column). It should not work when both sides have a onetoone mapping since they bounce the responsiblity back and forth.
Also the classes look a bit overcomplicated when all you need is to store the bytes somewhere else.
public class MusicInfoRepo
{
public virtual long Id { get; private set; }
public virtual MusicImageRepo Image { get; private set; }
public MusicInfo(byte[] image)
{
this.Image = new MusicImageRepo(this, image);
}
}
public class MusicImageRepo
{
public virtual MusicInfoRepo MusicInfo { get; private set; }
public virtual byte[] Blob { get; set; }
}
public class MusicInfoRepoMap : HighLowClassMapping<MusicInfoRepo>
{
public MusicInfoRepoMap()
{
Table("MusicInfo");
Id(f => f.Id, m => m.Generator(Generators.HighLow, HighLowMapper));
OneToOne(f => f.Image, m => m.Cascade(Cascade.All));
}
}
public class MusicImageRepoMap : ClassMapping<MusicImageRepo>
{
public MusicImageRepoMap()
{
Table("MusicImage");
ComposedId(m => m.ManyToOne(x => x.MusicInfo));
Property(f => f.Blob, m =>
{
m.NotNullable(true);
m.Column(c => c.SqlType("VARBINARY(MAX)"));
m.Length(Int32.MaxValue);
m.Update(false);
});
}
}
Note: think about it if the seperation between DomainModel and MappedModel really makes sense. NHibernate goes to great length supporting mapping of DomainModels.
I've created the following domain classes:
public class Car
{
public virtual int Id { get; set; }
public virtual string Registration { get; set; }
public virtual User ResponsibleContact { get; set; }
protected Car()
{}
public Fahrzeug(User responsibleContact, string registration)
{
ResponsibleContact = responsibleContact;
Registration = registration;
ResponsibleContact.Cars.Add(this);
}
}
public class User
{
public virtual int Id { get; set; }
public virtual byte[] EncryptedUsername { get; set; }
public virtual byte[] EncryptedPassword { get; set; }
public virtual IList<Car> Cars { get; private set; }
public virtual string Username
{
get
{
var decrypter = UnityContainerProvider.GetInstance().UnityContainer.Resolve<IRijndaelCrypting>();
return decrypter.DecryptString(EncryptedUsername);
}
}
protected User()
{ }
public User(byte[] encryptedUser, byte[] encryptedPassword)
{
Cars = new List<Car>();
EncryptedUsername = encryptedUser;
EncryptedPassword = encryptedPassword;
}
}
and the mapping classes:
public class CarMap : ClassMap<Car>
{
public CarMap()
{
Id(c => c.Id).GeneratedBy.Native();
Map(c => c.Registration);
References(c => c.ResponsibleContact).Not.Nullable();
}
}
public class UserMap : ClassMap<User>
{
public UserMap()
{
Id(st => st.Id).GeneratedBy.Native();
Map(st => st.EncryptedUsername).Column("Username");
Map(st => st.EncryptedPassword).Column("Password");
HasMany(st => st.Cars).Inverse().AsBag();
}
}
If I query some Member objects, I get the members, but the cars collection is empty!
If I query some Cars I got all the cars with the right Member. But within the member, the cars collection is also empty!
Is there anybody who has an Idea of what can happened?
you have to make sure the foreign key column of the collection and the reference is the same otherwise there is a mismatch.
References(c => c.ResponsibleContact, "ResponsibleContact_id").Not.Nullable();
and
HasMany(st => st.Cars).Inverse().KeyColumn("ResponsibleContact_id");
How to write mappings in new NHibernate Mapping-By-Code in Table Per Subclass strategy for this classes:
public class Person
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
}
public class JuridicalPerson : Person
{
public virtual int Id { get; set; }
public virtual string LegalName { get; set; }
}
public class PrivatePerson : Person
{
public virtual int Id { get; set; }
public virtual bool Sex { get; set; }
}
Here is a possible mapping in a slighly abbreviated form
public class PersonMapping : ClassMapping<Person>
{
public PersonMapping()
{
Table("person");
Id(x => x.Id, m => m.Generator(Generators.Native));
Property(x => x.Name);
}
}
public class JuridicalPersonMapping : JoinedSubclassMapping<JuridicalPerson>
{
public JuridicalPersonMapping()
{
Table("juridical_person");
Key(m => m.Column("person_id"));
Property(x => x.LegalName);
}
}
public class PrivatePersonMapping : JoinedSubclassMapping<PrivatePerson>
{
public PrivatePersonMapping()
{
Table("private_person");
Key(m => m.Column("person_id"));
Property(x => x.Sex);
}
}
You don't need to duplicate declaration of the Id property in the derived classes. It's inherited from the parent Person class.
I am trying to map a list containing instances of different types that all implements a common interface with Fluent NHibernate.
Below is a simplified example of how I want my model to look like. I want all types of questions to be stored in the same table and all types of answers to be stored in one table per type.
When using the Mapping in the example for survey Nhibernate treats all questions as IQuestion, and all Answers as IAnswer
What am I doing wrong?
public class SurveyMap : ClassMap<Survey>
{
public SurveyMap()
{
Id(x => x.Id);
Map(x => x.Name);
HasMany(x => x.Questions).Cascade.All();
HasMany(x => x.Answers).Cascade.All();
}
}
public class BoolAnswerMap : SubclassMap<BoolAnswer>
{
public BoolAnswerMap()
{
Map(x => x.Value).Nullable();
References(x => x.Question);
}
}
public class DecimalAnswerMap : SubclassMap<DecimalAnswer>
{
public DecimalAnswerMap()
{
Map(x => x.Value).Nullable();
References(x => x.Question);
}
}
public class AnswerMap : ClassMap<IAnswer>
{
public AnswerMap()
{
Id(x => x.Id);
}
}
public class BoolQuestionMap : SubclassMap<BoolQuestion>
{
public BoolQuestionMap()
{
//HasMany(x => x.SubQuestions).Cascade.All(); -- Let's leave the subquestions for now
}
}
public class DecimalQuestionMap : SubclassMap<DecimalQuestion>
{
public DecimalQuestionMap()
{
}
}
public class QuestionMap : ClassMap<IQuestion>
{
public QuestionMap()
{
Id(x => x.Id);
Map(x => x.QuestionText).Not.Nullable();
DiscriminateSubClassesOnColumn("Type");
}
}
public class Survey{
private IList<IQuestion> questions = new List<IQuestion>();
private IList<IAnswer> answers = new List<IAnswer>();
public virtual string Name { get; set; }
public virtual IEnumerable<IQuestion> Questions { get { return questions; } }
public virtual IEnumerable<IAnswer> Answers { get { return answers; } }
public virtual void AddQuestion(IQuestion question){
questions.Add(question);
}
public virtual void AddAnswer(IAnswer answer{
answers.Add(answer);
}
}
public interface IQuestion{
int Id { get; set; };
string QuestionText { get; set; }
}
public interface IAnswer{
int Id { get; set; }
IQuestion Question { get; set; }
}
public class BoolQuestion: IQuestion{
private IList<IQuestion> subQuestions = new List<IQuestion>();
int Id { get; set; };
string QuestionText { get; set; }
public virtual IEnumerable<IQuestion> SubQuestions { get { return subQuestions; } }
public virtual void AddSubQuestion(IQuestion question){
subQuestions.Add(question);
}
}
//You could argue that this could be just Question (but this is a simplified example)
public class DecimalQuestion: IQuestion{
int Id { get; set; };
string QuestionText { get; set; }
}
public class BoolAnswer : IAnswer {
public int Id { get; set; }
public IQuestion Question { get; set; }
bool Value { get; set; }
}
public class DecimalAnswer : IAnswer {
public int Id { get; set; }
public IQuestion Question { get; set; }
decimal Value { get; set; }
}
ReferencesAny should do what you want.