I am getting the following error
One or more validation errors were detected during model generation:
\tSystem.Data.Entity.Edm.EdmAssociationEnd: : Multiplicity is not valid in Role 'UserRoles_Roles_Source' in relationship 'UserRoles_Roles'. Because the Dependent Role refers to the key properties, the upper bound of the multiplicity of the Dependent Role must be '1'.
My entities and the associated mappings are defined as follows,
public class UserProfile
{
public UserProfile()
{
UserUserRoles = new List<UserRoles>();
}
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public virtual ICollection<UserRoles> UserUserRoles { get; set; }
}
public class Roles
{
public Roles()
{
RoleUserRoles = new List<UserRoles>();
}
public int RoleId { get; set; }
public string RoleName { get; set; }
public virtual ICollection<UserRoles> RoleUserRoles { get; set; }
}
public class UserRoles
{
public int UserId { get; set; }
public int RoleId { get; set; }
public virtual UserProfile User { get; set; }
public virtual Roles Roles { get; set; }
}
//Mappings
public UserProfileMap()
{
// Primary Key
HasKey(t => t.UserId);
// Properties
Property(t => t.UserName)
.HasMaxLength(56);
// Table & Column Mappings
ToTable("UserProfile");
Property(t => t.UserId).HasColumnName("UserId");
Property(t => t.UserName).HasColumnName("UserName");
}
public class RolesMap : EntityTypeConfiguration<Roles>
{
public RolesMap()
{
// Primary Key
HasKey(t => t.RoleId);
// Properties
Property(t => t.RoleName)
.HasMaxLength(256);
// Table & Column Mappings
ToTable("webpages_Roles");
Property(t => t.RoleId).HasColumnName("RoleId");
Property(t => t.RoleName).HasColumnName("RoleName");
}
}
public class UserRolesMap : EntityTypeConfiguration<UserRoles>
{
public UserRolesMap()
{
// Primary Key
HasKey(t => t.UserId);
HasKey(t => t.RoleId);
// Table & Column Mappings
ToTable("webpages_UsersInRoles");
Property(t => t.UserId).HasColumnName("UserId");
Property(t => t.RoleId).HasColumnName("RoleId");
// Relationships
HasRequired(t => t.User)
.WithMany(t => t.UserUserRoles)
.HasForeignKey(d => d.UserId);
HasRequired(t => t.Roles)
.WithMany(t => t.RoleUserRoles)
.HasForeignKey(d => d.RoleId);
}
}
what am I doing wrong?
Per the comments:
A combined primary key should be constructed as HasKey(t => new { t.UserId, t.RoleId });
It looks like you want to create a many-to-many relation between models. In that case you do not need the class UserRoles, it will be generated by EF when using this scenario:
public class User
{
// other properties
public virtual IList<Role> Roles {get;set;}
}
public class Role
{
// other properties
public virtual IList<User> Users {get;set;}
}
However, if you do want the UserRoles model to for instance store additional information you need to make the mapping manually in for example the OnModelCreating() function of the DbContext class.
Related
I have an existing database that has a PK that is a numberic(18,0) and a FK that is an int. When I try to use the navigation property EF throws an invalid cast exception.
Is there a way to map this relationship that will sort out the invalid cast?
In the code below promo_cfg.pc_id is numeric(18,0) and promo.pc_id is int.
public class PromotionMap : EntityTypeConfiguration<Promotion>
{
public PromotionMap()
{
// Primary Key
this.HasKey(p => p.PromotionId);
// Properties
// table and column mappings
this.ToTable("promo");
this.Property(p => p.PromotionId).HasColumnName("p_id");
this.Property(p => p.PromotionConfigId).HasColumnName("pc_id");
this.Property(p => p.PromotionCode).HasColumnName("p_code");
this.HasRequired(t => t.PromotionConfig)
.WithMany(t => t.Promotions)
.HasForeignKey(d => new { d.PromotionConfigId });
}
}
public class Promotion
{
public decimal PromotionId { get; set; }
public int PromotionConfigId { get; set; }
public string PromotionCode { get; set; }
}
public PromotionConfigMap()
{
// Primary Key
this.HasKey(s => s.PromotionConfigId);
// Properties
// Table and Column mappings
this.ToTable("promo_cfg");
this.Property(p => p.PromotionConfigId).HasColumnName("pc_id");
this.Property(p => p.AllowOrders).HasColumnName("allow_orders");
this.HasOptional(p => p.Promotions).WithRequired().Map(x => x.MapKey("pc_id"));
}
public class PromotionConfig
{
public int PromotionConfigId { get; set; }
public int AllowOrders { get; set; }
public virtual ICollection<Promotion> Promotions { get; set; }
}
May be, with a big MAY, with a non materialized FK:
HasOptional(x => x.SomeProperty).WithMany().Map(x => x.MapKey("intDbColumnName"));
========================================================
I remove all unneeded code, the following should do:
public class Promotion
{
public decimal PromotionId { get; set; }
//Here you do not materialize the FK
public PromotionConfig PromotionConfig { get; set; }
}
public class PromotionConfig
{
public decimal PromotionConfigId { get; set; } // you can't do otherwise as
//you must declare a PK for EF
public virtual ICollection<Promotion> Promotions { get; set; }
}
public class PromotionMap : EntityTypeConfiguration<Promotion>
{
public PromotionMap()
{
// Primary Key
this.HasKey(p => p.PromotionId);
// Properties
// table and column mappings
this.ToTable("promo");
this.Property(p => p.PromotionId).HasColumnName("p_id");
//if I well understand pc_id is an int that relates to a decimal
this.HasRequired(p => p.PromotionConfig)
.WithMany(pc => pc.Promotions)
.Map(p => p.MapKey("pc_id"));
}
}
public class PromotionConfigMap : EntityTypeConfiguration<PromotionConfig> {
public PromotionConfigMap()
{
// Primary Key
this.HasKey(s => s.PromotionConfigId);
// Properties
// Table and Column mappings
this.ToTable("promo_cfg");
}
}
So I'm trying to use the MVC 4 internet application template and the UserProfile database tables it creates for accounts and then add tables that have dependencies on the UserProfile table for additional information.
The model would be UserProfile 0 ---> 1 UserType1 and UserProfile 0 ----> UserType2
where the userprofile table may have a dependent record in UserType1 and may have a dependent record in UserType2 and if there is an entry in either UserType1 or UserType2 its primary key is a foreign key that is the UserId from User Profiles
The POCO is:
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string Email { get; set; }
public string UserName { get; set; }
public int type { get; set; }
public virtual UserType1 UserType1 { get; set; }
public virtual UserType2 UserType2 { get; set; }
public class UserType1
{
[key,ForeignKey("UserProfile")]
public virtual int UserId {get;set;}
public int myval {get;set;}
public UserProfile UserProfile {get; set;}
}
public class UserType2 //same as usertype 1
I've tried adding model mapping statements but to no avail
Model mapping data for user profile:
public class UserProfileMap : EntityTypeConfiguration<UserProfile>
{
public UserProfileMap()
{
// Primary Key
this.HasKey(t => t.UserId);
// Properties
this.Property(t => t.Email)
.IsRequired()
.HasMaxLength(56);
this.Property(t => t.UserName)
.IsRequired()
.HasMaxLength(50);
// Table & Column Mappings
this.ToTable("UserProfile");
this.Property(t => t.UserId).HasColumnName("UserId");
this.Property(t => t.Email).HasColumnName("Email");
this.Property(t => t.UserName).HasColumnName("UserName");
this.Property(t => t.UserType).HasColumnName("UserType");
this.HasOptional(e => e.UserType1).WithRequired();
The model mapping data for usertypes looks like this:
public class UserType1 : EntityTypeConfiguration<UserType1>
{
public UserType1Map()
{
// Primary Key
this.HasKey(t => t.UserId);
// Properties
this.Property(t => t.UserId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
this.HasRequired(t => t.UserProfile).WithOptional();
this.Property(t => t.Company)
.IsRequired()
.HasMaxLength(50);
// Table & Column Mappings
this.ToTable("UserType1");
this.Property(t => t.UserId).HasColumnName("UserId");
this.Property(t => t.Company).HasColumnName("Company");
// Relationships
this.HasRequired(t => t.UserProfile).WithOptional();
}
}
But I always get this error Unable to determine the principal end of an association between the types 'myApp.Models.UserType1' and 'myApp.Models.UserProfile'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
what did I miss?
Configure the relationship for only one entity (in your case, in UserProfileMap). Explicitly specify the property in the .WithRequired() call as well. Here's demo code that worked for me:
modelBuilder.Entity<SharedKeyRequired>()
.HasOptional( skr => skr.SharedKeyOptional )
.WithRequired( sko => sko.SharedKeyRequired );
public class SharedKeyRequired
{
public int SharedKeyRequiredId { get; set; }
public virtual SharedKeyOptional SharedKeyOptional { get; set; }
}
public class SharedKeyOptional
{
public int SharedKeyOptionalId { get; set; }
public virtual SharedKeyRequired SharedKeyRequired { get; set; }
}
Moho, I voted your answer as correct but I thought I would put MVC equivalent source here for those that might be confused by the verbage.
Desired end result is using the MVC AccountModel and adding code-first tables which have a foreignkey as their primary keys to extend the UserProfile table with an optional 1 to 1 relationship
Modify your user profile class to add a virtual reference to your new table
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public virtual UserInfo UserInfo { get; set; }
}
create your new table I chose to use Data Notation you could specify this in modelBuilder as
modelBuilder.Entity().HasKey(k => k.UserId);
modelBuilder.Entity().Property(ui => ui.UserId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
public class UserInfo
{
[Key,ForeignKey("UserProfile")] //use above or specify this
public int UserId { get; set; }
public virtual UserProfile UserProfile { get; set; }
public int somevalue { get; set; }
public string name { get; set; }
}
override your OnModelCreating member of your context class and specify the relationship as Moho stated
public class UsersContext : DbContext
{
public UsersContext()
: base("DefaultConnection")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// modelBuilder.Entity<UserInfo>().HasKey(k => k.UserId);
// modelBuilder.Entity<UserInfo>().Property(ui => ui.UserId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
modelBuilder.Entity<UserProfile>().HasOptional(ui => ui.UserInfo).WithRequired(up => up.UserProfile);
base.OnModelCreating(modelBuilder);
}
public DbSet<UserProfile> UserProfiles { get; set; }
public DbSet<UserInfo> UserInfoes { get; set; }
}
I have an existing database with two tables: MemData and MemPhone.
MemData has the following structure
uidMemberId (PK, uniqueidentifier not null)
strFirstName (varchar(50), null)
strLastName (varchar(50), null)
MemPhone has the following structure
uidMemberId (uniqueidentifier not null)
strPhoneNumber (varchar(50), null)
There's no PK on the MemberPhoneNumber table. The two tables are joined by uidMemberId but no foreign keys have been set up in the database.
My MemData Model looks like this:
[Table("MemData")]
public class Member
{
[Key]
public Guid MemberId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual IList<MemberPhoneNumber> MemberPhoneNumbers { get; set; }
}
With the configuration map looking like this:
public MemberMap()
{
Property(t => t.MemberId).HasColumnName("uidMemberID");
Property(t => t.FirstName).HasColumnName("strFirstName");
Property(t => t.LastName).HasColumnName("strLastName");
HasMany(x => x.MemberPhoneNumbers);
}
My MemPhone Model looks like this:
[Table("MemPhone")]
public class MemberPhoneNumber
{
[Key]
public Guid MemberId { get; set; }
public string PhoneNumber { get; set; }
public virtual Member Member { get; set; }
}
With the configuration map looking like this:
public MemberPhoneNumberMap()
{
Property(t => t.MemberId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
Property(t => t.MemberId).HasColumnName("uidMemberID");
Property(t => t.PhoneNumber).HasColumnName("strPhone");
}
In my MVC app, when I call
Uow.Members.GetAll().Include(p => p.MemberPhoneNumbers).ToList()
I get the following error
Invalid column name 'Member_MemberId'.
It should be looking for MemData_uidMemberId instead but I can't figure out what I've missed in the configuration.
Thanks
By default foreign key name will be propertyName _ entityId. That's why EF tries to map to Member_MemberId column. Provide foreign key configuration for one-to-many relationship
public class MemberMap : EntityTypeConfiguration<Member>
{
public MemberMap()
{
ToTable("MemData");
HasKey(m => m.MemberId);
Property(m => m.MemberId).HasColumnName("uidMemberID");
Property(m => m.FirstName).HasColumnName("strFirstName");
Property(m => m.LastName).HasColumnName("strLastName");
HasMany(x => x.MemberPhoneNumbers)
.WithRequired(p => p.Member)
.HasForeignKey(p => p.MemberId);
}
}
Also keep in mind, that you can configure key and table with fluent configuration, you don't need to pollute your entity with data annotations attributes.
Is it possible to have a different schema name on correlation tabels than [dbo]?
I'm using code first.
Example:
ApplicationRole.cs
public class ApplicationRole
{
public Guid ApplicationRoleId { get; set; }
public string Name { get; set; }
public virtual ICollection<ADGroup> ADGroups { get; set; }
}
ADGroup.cs
public class ADGroup
{
public Guid ADGroupId { get; set; }
public string Name { get; set; }
public virtual ICollection<ApplicationRole> ApplicationRoles { get; set; }
}
ApplicationRoleConfiguration.cs
public class ApplicationRoleConfiguration : EntityTypeConfiguration<ApplicationRole>
{
public ApplicationRoleConfiguration()
{
ToTable("T_ApplicationRoles", "LabConfig");
this.HasKey(a => a.ApplicationRoleId);
this.Property(t => t.ApplicationRoleId)
.HasColumnName("ApplicationRole_GUID")
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
}
ADGroupConfiguration.cs
public class ADGroupConfiguration : EntityTypeConfiguration<ADGroup>
{
public ADGroupConfiguration()
{
ToTable("T_ADGroups", "LabConfig");
this.HasKey(a => a.ADGroupId);
this.Property(t => t.ADGroupId)
.HasColumnName("ADGroup_GUID")
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
// correlation table should also get schema [LabConfig]
this.HasMany(o => o.ApplicationRoles)
.WithMany(r => r.ADGroups)
.Map(m =>
{
m.MapLeftKey("ADGroup_GUID");
m.MapRightKey("ApplicationRole_GUID");
ToTable("T_ApplicationRoleADGroups", "LabConfig");
});
}
}
But the result on the database is always:
[LabConfig].[T_ADGroups]
[LabConfig].[T_ApplicationRoles]
[dbo].[ApplicationRoleADGroups]
Any ideas? I spent hours for this to work with my desired schema without any success.
In my case i did something stupid i didn't see...
Compare the original ADGroupConfiguration.cs with this:
public class ADGroupConfiguration : EntityTypeConfiguration<ADGroup>
{
public ADGroupConfiguration()
{
ToTable("T_ADGroups", "LabConfig");
this.HasKey(a => a.ADGroupId);
this.Property(a => a.ADGroupId)
.HasColumnName("ADGroup_GUID")
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.Property(t => t.Name).HasColumnName("Name").IsRequired();
// the Mapping was causing the error.
// this Mapping is correct now
this.HasMany(o => o.ApplicationRoles)
.WithMany(r => r.ADGroups)
.Map(m => m.MapLeftKey("ADGroup_GUID")
.MapRightKey("ApplicationRole_GUID")
.ToTable("T_ApplicationRoleADGroups", "LabConfig"));
}
}
Hence my mapping had an error it was hiding the real problem i was searching for...
Always double check the mappings!
By code-first approach (but with an existing db schema), we are trying to map 2 different entities (Customer and Resource) to the same table. Both entities has the same keys and mapping.
However, when running the app, we have a runtime error telling us that mysterious message:
System.InvalidOperationException: Type 'Resource' cannot be mapped to table 'CLIENT' since type 'Customer' also maps to the same table and their primary key names don't match. Change either of the primary key property names so that they match.
Example:
public class EntityA
{
public string ID { get; set; }
public string Discriminator { get; set; }
public string TimeStamp { get; set; }
}
public class EntityB
{
public string ID { get; set; }
public string Discriminator { get; set; }
public string CreatedBy { get; set; }
}
public class EntityAConfiguration : EntityTypeConfiguration<EntityA>
{
public EntityAConfiguration()
{
HasKey(x => new {x.ID, x.Discriminator } );
Property(x => x.ID).HasColumnName("MyTable_ID").HasDatabaseGenerationOption(DatabaseGenerationOption.None);
Property(x => x.Discriminator).HasColumnName("MyTable_Discriminator").HasDatabaseGenerationOption(DatabaseGenerationOption.None);
Property(x => x.TimeStamp).HasColumnName("MyTable_TimeStamp");
ToTable("MyTable");
}
}
public class EntityBConfiguration : EntityTypeConfiguration<EntityB>
{
public EntityBConfiguration()
{
HasKey(x => new { x.ID, x.Discriminator });
Property(x => x.ID).HasColumnName("MyTable_ID").HasDatabaseGenerationOption(DatabaseGenerationOption.None);
Property(x => x.Discriminator).HasColumnName("MyTable_Discriminator").HasDatabaseGenerationOption(DatabaseGenerationOption.None);
Property(x => x.CreatedBy).HasColumnName("MyTable_CreatedBy");
ToTable("MyTable");
}
}
The above code is similar to our Customer/Resource code (but simpler for the explanation!).
However, get get the same Error message, telling us that EntityA and EntityB cannot be mapped to the same table because their primary key names don't match.
Any idea of what is wrong with our mapping?
Any idea how we could different entities to the same table?
Thanks for your help
Mapping 2 entity to one table requires that you create a Complex Type or Table Per Hierarchy (TPH). You can't just map 2 entities to one table like this. Let me know which one is better describe your domain model and I will provide you with the required object model/fluent API code.
Update: TPH Mapping:
public abstract class EntityBase
{
[Column(Name = "MyTable_ID")]
public string ID { get; set; }
[Column(Name = "MyTable_Discriminator")]
public string Discriminator { get; set; }
}
public class EntityA : EntityBase
{
[Column(Name = "MyTable_TimeStamp")]
public string TimeStamp { get; set; }
}
public class EntityB : EntityBase
{
[Column(Name = "MyTable_CreatedBy")]
public string CreatedBy { get; set; }
}
public class StackoverflowTestContext : DbContext
{
public DbSet<EntityBase> Entities { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<EntityBase>()
.HasKey(x => new { x.ID, x.Discriminator });
modelBuilder.Entity<EntityBase>()
.Map<EntityA>(m => m.Requires("TPHDiscriminator")
.HasValue("yourDesiredValueForA"))
.Map<EntityB>(m => m.Requires("TPHDiscriminator")
.HasValue("yourDesiredValueForB"))
.ToTable("MyTable");
}
}