Fluent NHibernate Mapping Problem (Override) - asp.net

I have tried to make an inheritation mapping. There are two
alternative. One alternative is with JoinedSubClass (that is
deprecated and give me a warning) and the other and newer is with
SubClassMap.
But I get an error that I have duplicate entity/object mapping. What
could be the problem?
With the JoinedSubClass it runs. Here are the Codes of my two Objects
and the MappingFile with JoinedSubClass which runs, later there are
the code of my mapping file with "SubClassMap" which doesn't run....
Objects:
public class Person {
public virtual int Id { get; private set; }
public virtual string Vorname { get; set; }
public virtual string Nachname { get; set; }
public virtual string Email { get; set; }
public virtual Adresse Adresse { get; set; }
public Person() {
}
}
public class PersonQuelle : Person, IQuelle {
public virtual string Beschreibung { get; set; }
public virtual Institution Institution { get; set; }
public virtual IList<MediaDatei> MediaDateien { get; set; }
public PersonQuelle() {
MediaDateien = new List<MediaDatei>();
}
public virtual void HinzufuegenMediaDatei(MediaDatei mediaDatei) {
mediaDatei.PersonQuelle = this;
MediaDateien.Add(mediaDatei);
}
public virtual void LoeschenMediaDatei(MediaDatei mediaDatei)
{
mediaDatei.PersonQuelle = null;
MediaDateien.Remove(mediaDatei);
}
}
Mapping Files:
public class PersonMap : ClassMap<Person> {
public PersonMap() {
Id(x => x.Id);
Map(x => x.Vorname);
Map(x => x.Nachname);
Map(x => x.Email);
References(x => x.Adresse);
JoinedSubClass<PersonQuelle>("personQuelle_Id", m => {
m.Map(c => c.Beschreibung);
m.References(c => c.Institution);
m.HasMany(c => c.MediaDateien).Inverse().Cascade.All();
});
JoinedSubClass<MMAdminBenutzer>("mmAdminBenutzer_Id", m =>
{
m.Map(c => c.Kuerzel);
m.Map(c => c.Passwort);
m.Map(c => c.Benutzerrolle);
m.HasMany(c => c.MediaDateien).Inverse().Cascade.All();
m.HasMany(c => c.Kategorien).Inverse().Cascade.All();
});
}
}
But why it doesn't run when I do that with the same Objects however
with this mapping file??
Mapping File with SubClassMap:
public class PersonMap : ClassMap<Person> {
public PersonMap() {
Id(x => x.Id);
Map(x => x.Vorname);
Map(x => x.Nachname);
Map(x => x.Email);
References(x => x.Adresse);
}
}
public class PersonQuelleMap : SubclassMap<PersonQuelle>
{
PersonQuelleMap()
{
Map(c => c.Beschreibung);
References(c => c.Institution);
HasMany(c => c.MediaDateien).Inverse().Cascade.All();
}
}

It's hard to tell without the error that you get, but I think you are missing a call to KeyColumn("personQuelle_Id") in your SubclassMap.

Related

No suitable constructor was found for entity type HierarchyId in abp Project

The table is created in the database, but every request in the software to get database information throws this error:
No suitable constructor was found for entity type 'HierarchyId'. The following constructors had parameters that could not be bound to properties of the entity type: cannot bind 'value' in 'HierarchyId(SqlHierarchyId value)'.
This is my Entity class
public class OrganizationalPosition: AuditedAggregateRoot<long>
{
public OrganizationalPosition()
{
}
public OrganizationalPosition(string title, HierarchyId organizationNode,HierarchyId parentNode)
{
SetTitle(title);
Node = organizationNode;
ParentNode = parentNode;
NodeText = Node.ToString();
NodeLevel = Node.GetLevel();
}
public string Title { get; private set; }
public HierarchyId Node { get; private set; }
public HierarchyId ParentNode { get; set; }
public long ParentId { get; set; }
public string NodeText { get; set; }
public int NodeLevel { get; set; }
public OrganizationalPosition Parent { get; set; }
public ICollection<OrganizationalPosition> Children { get; set; }
public ICollection<OrganizationUser> Users { get; set; }
public void SetTitle(string title)
{
if (title.Length is < 2 or > 100)
throw new FormatException($"{nameof(title)} is not valid");
Title = title;
}
}
This is my DbSet
public DbSet<OrganizationalPosition> OrganizationalPositions { get; set; }
This is my Configure
builder.Entity<OrganizationalPosition>(b =>
{
b.ToTable(HumanResourceDbProperties.DbTablePrefix + "OrganizationalPositions",
HumanResourceDbProperties.DbSchema);
b.ConfigureByConvention();
b.HasOne(x => x.Parent)
.WithMany(x => x.Children)
.HasForeignKey(x => x.ParentId)
.OnDelete(DeleteBehavior.NoAction)
.IsRequired();
b.Property(x => x.Node)
.IsRequired();
b.Property(x => x.Title)
.HasMaxLength(200)
.IsRequired();
b.Property(x => x.NodeText)
.HasMaxLength(200)
.IsRequired();
b.Property(x => x.NodeLevel)
.IsRequired();
b.HasIndex(x => new { x.Node }).IsUnique();
});
This is my MigrationsDbContext
public HumanResourceHttpApiHostMigrationsDbContext CreateDbContext(string[] args)
{
var configuration = BuildConfiguration();
var builder = new
DbContextOptionsBuilder<HumanResourceHttpApiHostMigrationsDbContext>()
.UseSqlServer(configuration.GetConnectionString("HumanResource"),
x => x.UseHierarchyId());
return new HumanResourceHttpApiHostMigrationsDbContext(builder.Options);
}
this is my package that I am installed
<PackageReference Include="EntityFrameworkCore.SqlServer.HierarchyId" Version="3.0.1" />
<PackageReference Include="Volo.Abp.Ddd.Domain" Version="5.3.2" />
<ProjectReference Include="..\YesnaPars.HumanResource.Domain.Shared\YesnaPars.HumanResource.Domain.Shared.csproj" />
This link didn't help me either
No suitable constructor found for entity type HierarchyId

EF Core Entity Circular Reference

I am using C#.net and ef core. I have the models below. When I get my list of competitions, I want to only get my related user. However, I am getting the User and all the User's competitions. How can I achieve this? I had to do the following to get my list of competitions to show:
.AddJsonOptions(opt => opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore)
public partial class Competition
{
public int CompetitionId { get; set; }
public int UserId { get; set; }
public User User { get; set; }
}
public partial class User
{
public int UserId { get; set; }
public string Email { get; set; }
public string UserName { get; set; }
public ICollection<Competition> Competitions { get; set; }
}
I have an api that uses entity framework to make calls to my database using the models describe above. The call in my api that causes the circular reference is the following:
[Produces("application/json")]
[Route("api/Competitions")]
public class CompetitionsController : Controller
{
private readonly ApplicationDBContext _context;
public CompetitionsController(ApplicationDBContext context)
{
_context = context;
}
// GET: api/Competitions
[HttpGet]
public IEnumerable<Competition> GetCompetitions()
{
//return _context.Competitions;
return _context.Competitions
.Include(u => u.User).ToList();
}
}
Below is my onmodelcreating code block in my ApplicationDBContext class:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Competition>(entity =>
{
entity.HasKey(e => e.CompetitionId);
entity.HasOne(d => d.User)
.WithMany(p => p.Competitions)
.HasForeignKey(d => d.UserId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Competitions_Users");
});
modelBuilder.Entity<User>(entity =>
{
entity.HasKey(e => e.UserId);
entity.HasIndex(e => e.UserName)
.HasName("UC_UserName")
.IsUnique();
entity.Property(e => e.Email)
.HasMaxLength(40)
.IsUnicode(false);
entity.Property(e => e.UserName)
.HasMaxLength(40)
.IsUnicode(false);
});
}
Old question, but in case someone still looking.
One solution is:
services.AddMvc()
.AddJsonOptions(options => {
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
You should have ignored Competitions collection in user model while building.
modelBuilder.Entity<User>()
.Ignore(b => b.Competitions);

Entity Framework 6 - Property name 'varchar' is already defined

I'am using EF6 and code firt in project, but i get this error on creating the model
Name: Each property name in a type must be unique. Property name 'varchar' is already defined.
below is my entity and my map
public class Menu
{
public Menu()
{
ListaFilhos = new List<Menu>();
}
public Int32 MenuID { get; set; }
public String Nome { get; set; }
public String Action { get; set; }
public String Controller { get; set; }
public String Url { get; set; }
public Int32? Pai { get; set; }
public Boolean? Ativo { get; set; }
public virtual List<Menu> ListaFilhos { get; set; }
}
Map
public class MenuMap : EntityTypeConfiguration<Entidade.Menu>
{
public MenuMap()
{
HasKey(x => x.MenuID);
Property(x => x.MenuID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(x => x.Pai).IsRequired();
Property(x => x.Nome).HasColumnType("varchar").HasMaxLength(100).IsRequired();
Property(x => x.Url).HasColumnName("varchar").HasMaxLength(250);
Property(x => x.Action).HasColumnName("varchar").HasMaxLength(50);
Property(x => x.Controller).HasColumnName("varchar").HasMaxLength(50);
Property(x => x.Ativo).IsRequired();
ToTable("Menu");
}
}
public class MenuGrupo
{
public MenuGrupo()
{
ListaMenu = new List<Menu>();
}
public Int32 MenuGrupoID { get; set; }
public Int32 MenuID { get; set; }
public virtual List<Menu> ListaMenu { get; set; }
}
public class MenuGrupoMap : EntityTypeConfiguration<Entidade.MenuGrupo>
{
public MenuGrupoMap()
{
HasKey(x => x.MenuGrupoID);
Property(x => x.MenuGrupoID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(x => x.MenuID).IsRequired();
ToTable("MenuGrupo");
}
}
I guess my problem is on MenuMap, when i remove in the OnModelCreate, all orther map working.
What i'am doing wrong?
tks

Validation failed for one or more entities. UserManager.AddToRole()

I'm developing a Web Api using ASP.NET MVC5 and I have successfully implemented a Custom IdentityUser.Like So
public partial class Authentication : IdentityUser
{
public Authentication()
{
this.LoginSessions = new List<LoginSession>();
}
[Required]
public string PersonId { get; set; }
public virtual Lecturer Lecturer { get; set; }
public virtual Student Student { get; set; }
public virtual ICollection<LoginSession> LoginSessions { get; set; }
}
with the following Maps
public class IdentityUserLoginConfiguration: EntityTypeConfiguration<IdentityUserLogin>
{
public IdentityUserLoginConfiguration()
{
HasKey(t => t.UserId);
}
}
public class IdentityRoleConfiguration : EntityTypeConfiguration<IdentityRole>
{
public IdentityRoleConfiguration()
{
HasKey(t => t.Id);
}
}
public class AuthenticationMap : EntityTypeConfiguration<Authentication>
{
public AuthenticationMap()
{
// Primary Key
this.HasKey(t => t.PersonId);
// Properties
this.Property(t => t.PersonId)
.IsRequired()
.HasMaxLength(14);
// Table & Column Mappings
this.ToTable("Authentication");
this.Property(t => t.PersonId).HasColumnName("PersonID");
// Relationships
this.HasOptional(t => t.Lecturer)
.WithOptionalPrincipal(t => t.Authentication);
this.HasOptional(t => t.Student)
.WithOptionalPrincipal(t => t.Authentication);
}
}
But now my problem is that when I'm adding a user to a Role Using the
UserManager.AddToRole()
method I get a DBValidationError
This is really worrying me and would like some help as soon as possible

Entity Framework - Multiple Many-To-Many Relationships

I am trying to describe the mapping to EF to create multiple many-to-many relationships between the following two entities (simplified):
Product:
public class Product
{
[Key]
public int ProductID { get; set; }
public string ProductName { get; set; }
public decimal Price { get; set; }
public virtual ICollection<Transaction> Transactions { get; set; }
public virtual ICollection<Transaction> RefundTransactions { get; set; }
public virtual ICollection<Transaction> VoidTransactions { get; set; }
}
Transaction:
public class Transaction
{
[Key]
public int TransactionID { get; set; }
public virtual ICollection<Product> Products { get; set; }
public virtual ICollection<Product> RefundProducts { get; set; }
public virtual ICollection<Product> VoidProducts { get; set; }
}
OnModelCreating:
modelBuilder.Entity<Transaction>()
.HasMany(m => m.Products)
.WithMany(t => t.Transactions)
.Map(m =>
{
m.ToTable("Transaction_Product_Mapping");
m.MapLeftKey("TransactionID");
m.MapRightKey("ProductID");
}
);
modelBuilder.Entity<Transaction>()
.HasMany(transaction => transaction.VoidProducts)
.WithMany(t => t.VoidTransactions)
.Map(m =>
{
m.ToTable("Transaction_Void_Product_Mapping");
m.MapLeftKey("TransactionID");
m.MapRightKey("VoidProductID");
}
);
modelBuilder.Entity<Transaction>()
.HasMany(m => m.RefundProducts)
.WithMany(t => t.Transactions)
.Map(m =>
{
m.ToTable("Transaction_Refund_Product_Mapping");
m.MapLeftKey("TransactionID");
m.MapRightKey("RefundProductID");
}
);
Exception:
Type Transaction_Products is not defined in namespace Nautix_EPOS.Models
Now, I think this may be because I am defining the mapping 3 times separately. And possibly overwriting the first with the second, and the second with the last.
Question:
How can I tell EF about the multiple many-to-many mappings between the same two tables?
I figured it out, it's because I used the same t.Transactions in the first and third declaration. I should have use t.RefundTransactions:
modelBuilder.Entity<Transaction>()
.HasMany(m => m.Products)
.WithMany(t => t.Transactions)
.Map(m =>
{
m.ToTable("Transaction_Product_Mapping");
m.MapLeftKey("TransactionID");
m.MapRightKey("ProductID");
}
);
modelBuilder.Entity<Transaction>()
.HasMany(transaction => transaction.VoidProducts)
.WithMany(t => t.VoidTransactions)
.Map(m =>
{
m.ToTable("Transaction_Void_Product_Mapping");
m.MapLeftKey("TransactionID");
m.MapRightKey("VoidProductID");
}
);
modelBuilder.Entity<Transaction>()
.HasMany(m => m.RefundProducts)
.WithMany(t => t.RefundTransactions)
.Map(m =>
{
m.ToTable("Transaction_Refund_Product_Mapping");
m.MapLeftKey("TransactionID");
m.MapRightKey("RefundProductID");
}
);

Resources