EF7, what is wrong with my relation here? - asp.net

The relation seams to be find and works with other example but when trying to get with all of the possible Include it fails with the error.
Widget widget = _dbContext.Widgets.Where(w => w.Id == id)
.Include(w => w.DataSource)
.ThenInclude(d => d.DataSourceParams)
.ThenInclude(p => p.DataSourceParamProc)
.ThenInclude(s => s.DataSourceParamProcParams)
.Include(w => w.DataSource)
.ThenInclude(d => d.DataSourceParams)
.ThenInclude(p => p.SelectOptions)
.FirstOrDefault();
POCO's:
public class Widget
{
public int Id { get; set; }
public string Title { get; set; }
public int DataSourceId { get; set; }
public string Colour { get; set; }
public string Icon { get; set; }
public virtual DataSource DataSource { get; set; }
}
public class DataSource
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string StoredProc { get; set; }
public string DataBaseName { get; set; }
public virtual ICollection<DataSourceParam> DataSourceParams { get; set; }
}
public class DataSourceParam
{
public int Id { get; set; }
public int DataSourceId { get; set; }
public string Name { get; set; }
public int TypeId { get; set; }
public virtual DataSource DataSource { get; set; }
public virtual DataSourceParamProc DataSourceParamProc { get; set; }
}
public class DataSourceParamProc
{
public int Id { get; set; }
public string StoredProc { get; set; }
public string DataBaseName { get; set; }
[ForeignKey("DataSourceParam")]
public int DataSourceParamId { get; set; }
public virtual DataSourceParam DataSourceParam { get; set; }
public virtual ICollection<DataSourceParamProcParam> DataSourceParamProcParams { get; set; }
}
public class DataSourceParamProcParam
{
public int Id { get; set; }
public string Name { get; set; }
public string DefaultValue { get; set; }
public int DataSourceParamProcId { get; set; }
}
public class SelectOption
{
public int Id { get; set; }
public string Value { get; set; }
public string Label { get; set; }
public int DataSourceParamId { get; set; }
public virtual DataSourceParam DataSourceParam { get; set; }
}
I'm getting error :
A column has been specified more than once in the order by list. Columns in the order by list must be unique.
If I comment this line it works:
Widget widget = _dbContext.Widgets.Where(w => w.Id == id)
.Include(w => w.DataSource)
.ThenInclude(d => d.DataSourceParams)
.ThenInclude(p => p.DataSourceParamProc)
//.ThenInclude(s => s.DataSourceParamProcParams)
.Include(w => w.DataSource)
.ThenInclude(d => d.DataSourceParams)
.ThenInclude(p => p.SelectOptions)
.FirstOrDefault();
Or If I comment this one it works as well:
Widget widget = _dbContext.Widgets.Where(w => w.Id == id)
.Include(w => w.DataSource)
.ThenInclude(d => d.DataSourceParams)
.ThenInclude(p => p.DataSourceParamProc)
.ThenInclude(s => s.DataSourceParamProcParams)
//.Include(w => w.DataSource)
// .ThenInclude(d => d.DataSourceParams)
// .ThenInclude(p => p.SelectOptions)
.FirstOrDefault();
If I separate this it works as well:
Widget widget = _dbContext.Widgets.Where(w => w.Id == id)
.Include(w => w.ChartAttributes)
.ThenInclude(c => c.ChartAttributeType)
.Include(w => w.WidgetCategory)
.Include(w => w.WidgetSeries)
.Include(w => w.WidgetType)
.FirstOrDefault();
DataSource ds = _dbContext.DataSources.Where(d => d.Id == widget.DataSourceId)
.Include(d => d.DataSourceParams)
.ThenInclude(p => p.SelectOptions)
.Include(d => d.DataSourceParams)
.ThenInclude(p => p.DataSourceParamProc)
.ThenInclude(s => s.DataSourceParamProcParams).FirstOrDefault();
widget.DataSource = ds;

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 Sqlite - FOREIGN KEY constraint failed migration - not nullable to nullable foreign key

I want to change a foreign key on my table from not nullable to nullable
Class name : DestinatairePartageDocument
public class DestinatairePartageDocument
{
[Key]
public int DestinatairePartageDocumentId { get; set; }
//[ForeignKey("Document")]
//public int DocumentId { get; set; }
[ForeignKey("Document")]
public int? DocumentId { get; set; }
public Document Document { get; set; }
//[ForeignKey("Examen")]
[NotMapped]
public int? ExamenId { get; set; }
//public Examen Examen { get; set; }
[ForeignKey("DestinatairePartage")]
public int DestinatairePartageId { get; set; }
public DestinatairePartage DestinatairePartage { get; set; }
public string CodeAccesDocument { get; set; }
public DateTime DateFinValiditeCodeAccesDocument { get; set; }
public string TypePartage { get; set; } /* PartageClassique, PartageCodeGenere */
public string StatutDocument { get; set; }
public bool PartageActive { get; set; }
public DateTime DateCreation { get; set; }
public DateTime DateDerniereModification { get; set; }
}
Old property setup :
[ForeignKey("Document")]
public int DocumentId { get; set; }
public Document Document { get; set; }
New property setup :
[ForeignKey("Document")]
public int? DocumentId { get; set; }
public Document Document { get; set; }
Upon doing this update, I then update my migration schema :
dotnet ef Migrations add UpdateDocumentNullable
And then I apply the modification to the database :
dotnet ef database update
But I then have the following error "FOREIGN KEY constraint failed" :
Here is the migration file generated :
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_DestinatairesPartageDocuments_Documents_DocumentId",
table: "DestinatairesPartageDocuments");
migrationBuilder.AddColumn<string>(
name: "StatutPartageExamen",
table: "Examens",
type: "TEXT",
nullable: true);
migrationBuilder.AlterColumn<int>(
name: "DocumentId",
table: "DestinatairesPartageDocuments",
type: "INTEGER",
nullable: true,
oldClrType: typeof(int),
oldType: "INTEGER");
migrationBuilder.AddColumn<int>(
name: "ExamenId",
table: "DestinatairesPartageDocuments",
type: "INTEGER",
nullable: true);
migrationBuilder.AddForeignKey(
name: "FK_DestinatairesPartageDocuments_Documents_DocumentId",
table: "DestinatairesPartageDocuments",
column: "DocumentId",
principalTable: "Documents",
principalColumn: "DocumentId",
onDelete: ReferentialAction.Restrict);
}
Below are the queries created from the migration :
My DbContext class :
public class ApplicationDbContext: IdentityDbContext<ApplicationUser>, IDataProtectionKeyContext
{
private readonly ILoggerFactory _loggerFactory;
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, ILoggerFactory loggerFactory) : base(options)
{
_loggerFactory = loggerFactory;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseLoggerFactory(_loggerFactory);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
//modelBuilder.Entity<DestinatairePartageDocument>()
// .Property(dpd => dpd.DocumentId)
// .HasDefaultValueSql("NULL");
//modelBuilder.Entity<DestinatairePartageDocument>()
// .HasOne(dpd => dpd.Document)
// .WithMany()
// .OnDelete(DeleteBehavior.Cascade);
//modelBuilder.Entity<DestinatairePartageDocument>()
// .HasOne("PortailWorker.Models.Document", "Document")
// .WithMany()
// .HasForeignKey("DocumentId");
modelBuilder.Entity<DestinatairePartageDocument>()
.Property(ap => ap.DateCreation)
.HasDefaultValueSql("CURRENT_TIMESTAMP");
modelBuilder.Entity<DestinatairePartageDocument>()
.Property(ap => ap.DateDerniereModification)
.HasDefaultValueSql("CURRENT_TIMESTAMP");
modelBuilder.Entity<Revendeur>()
.HasMany(r => r.ListeClients)
.WithOne(c => c.Revendeur);
modelBuilder.Entity<ClientWPFFetcher>()
.HasKey(cwf => new { cwf.ClientId, cwf.WPFFetcherId });
modelBuilder.Entity<ClientWPFFetcher>()
.Property(cwf => cwf.RelationActivated)
.HasDefaultValue(true);
modelBuilder.Entity<ClientWPFFetcher>()
.HasOne(cwf => cwf.Client)
.WithMany(c => c.ClientWPFFetchers)
.HasForeignKey(cwl => cwl.ClientId);
modelBuilder.Entity<ClientWPFFetcher>()
.HasOne(cwf => cwf.WPFFetcher)
.WithMany(c => c.ClientWPFFetchers)
.HasForeignKey(cwl => cwl.WPFFetcherId);
modelBuilder.Entity<ClientWorkerLocal>()
.HasKey(cwl => new { cwl.ClientId, cwl.WorkerLocalId });
modelBuilder.Entity<ClientWorkerLocal>()
.Property(cwl => cwl.RelationActivated)
.HasDefaultValue(true);
modelBuilder.Entity<ClientWorkerLocal>()
.HasOne(cwl => cwl.Client)
.WithMany(c => c.ClientWorkersLocal)
.HasForeignKey(cwl => cwl.ClientId);
modelBuilder.Entity<ClientWorkerLocal>()
.HasOne(cwl => cwl.WorkerLocal)
.WithMany(c => c.ClientWorkersLocal)
.HasForeignKey(cwl => cwl.WorkerLocalId);
modelBuilder.Entity<Client>()
.Property(ap => ap.ActivationStatus)
.HasDefaultValue(1);
modelBuilder.Entity<Revendeur>()
.Property(ap => ap.ActivationStatus)
.HasDefaultValue(1);
modelBuilder.Entity<WorkerLocal>()
.Property(ap => ap.ActivationStatus)
.HasDefaultValue(1);
modelBuilder.Entity<ConfigurationWorker>()
.Property(cw => cw.Jpeg2000LossyRate)
.HasDefaultValue(40);
modelBuilder.Entity<ConfigurationWorker>()
.Property(cw => cw.ActiverBackgroundServiceWorker)
.HasDefaultValue(true);
modelBuilder.Entity<WorkerLocal>()
.Property(ap => ap.EnLigne)
.HasDefaultValue(false);
modelBuilder.Entity<WorkerLocal>()
.Property(ap => ap.UtilisationCPUPourcentage)
.HasDefaultValue(0.00);
modelBuilder.Entity<WorkerLocal>()
.Property(ap => ap.UtilisationRAMPourcentage)
.HasDefaultValue(0.00);
modelBuilder.Entity<WorkerLocal>()
.Property(ap => ap.UtilisationStockagePourcentage)
.HasDefaultValue(0.00);
modelBuilder.Entity<MappingHL7>()
.Property(m => m.SegmentId)
.HasDefaultValue(1);
modelBuilder.Entity<MappingHL7>()
.Property(m => m.ChampsHL7RepetitionId)
.HasDefaultValue(1);
modelBuilder.Entity<MappingHL7>()
.Property(m => m.SousComposantHL7)
.HasDefaultValue(1);
modelBuilder.Entity<MappingHL7>()
.Property(m => m.TypeMessage)
.HasDefaultValue("Tous");
}
public DbSet<RegleTraitementImage> ReglesTraitementImage { get; set; }
public DbSet<CritereSelectionRegle> CriteresSelectionRegle { get; set; }
public DbSet<AETDemandeur> AETDemandeurs { get; set; }
public DbSet<DestinatairePartageDocument> DestinatairesPartageDocuments { get; set; }
public DbSet<WPFFetcher> WPFFetchers { get; set; }
public DbSet<ClientWPFFetcher> ClientsWPFFetchers { get; set; }
public DbSet<ExamenAEnvoyer> ExamensAEnvoyer { get; set; }
public DbSet<ImageAEnvoyer> ImagesAEnvoyer { get; set; }
public DbSet<WorkerLocal> WorkersLocal { get; set; }
public DbSet<DestinationHL7> DestinationsHL7 { get; set; }
public DbSet<MessageHL7> MessagesHL7 { get; set; }
public DbSet<Patient> Patients { get; set; }
public DbSet<Examen> Examens { get; set; }
public DbSet<Medecin> Medecins { get; set; }
public DbSet<Correspondant> Correspondants { get; set; }
public DbSet<ExamensCorrespondants> ExamensCorrespondants { get; set; }
public DbSet<MappingHL7> MappingHL7 { get; set; }
public DbSet<ConfigurationWorker> ConfigurationWorker { get; set; }
public DbSet<DocumentStatus> DocumentStatus { get; set; }
public DbSet<Document> Documents { get; set; }
public DbSet<DocumentLogEvents> DocumentLogEvents { get; set; }
public DbSet<DestinatairePartage> DestinatairesPartage { get; set; }
public DbSet<Client> Clients { get; set; }
public DbSet<Revendeur> Revendeurs { get; set; }
public DbSet<ClientWorkerLocal> ClientWorkersLocal { get; set; }
public DbSet<DataProtectionKey> DataProtectionKeys { get; set; }
public DbSet<MappingExamenCompression> MappingExamenCompression { get; set; }
}
Has anyone any idea how to prevent this error from happening ?
I have tried changing the onDelete constraint but it didn't change anything.
Thanks for your help !
After clearing the table everything works fine.
I think I had foreign key id from my previous tests that didn't exist anymore in the original table.
Sorry to bother you !

Entity Code First String FK values Uppercase or Lowercase

FK is linked to tbWarehouseUser 1 recording.
There are both lowercase and uppercase values in the tbWarehouseUser table.
How can I solve this problem ?
The classes are as follows;
private void Form1_Load(object sender, EventArgs e)
{
var model = new Model1();
var tbWarehouse = model.tbWarehouse.Where(c=> c.sWarehouse == "A1").FirstOrDefault();
var tbWarehouseUserList = tbWarehouse.tbWarehouseUser.ToList();
}
tbWarehouseUserList.Count record count 1.
1 record is coming. This problem causes sourced?
Recording picture
public partial class tbWarehouse
{
tbWarehouse()
{
tbWarehouseUser = new HashSet<tbWarehouseUser>();
}
[Key]
[StringLength(4)]
public string sWarehouse { get; set; }
public string WarehouseDescription { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<tbWarehouseUser> tbWarehouseUser { get; set; }
}
public partial class tbWarehouseUser
{
[Key]
[Column(Order = 0)]
[StringLength(4)]
public string sUserName { get; set; }
[Key]
[Column(Order = 1)]
[StringLength(4)]
public string sWarehouseName { get; set; }
public string sUserPass { get; set; }
public virtual tbWarehouse tbWarehouse { get; set; }
}
public partial class Model1 : DbContext
{
public Model1()
: base("name=Model1")
{
}
protected void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<tbWarehouse>()
.Property(e => e.sWarehouse)
.IsFixedLength()
.IsUnicode(false);
modelBuilder.Entity<tbWarehouse>()
.Property(e => e.WarehouseDescription)
.IsUnicode(false);
modelBuilder.Entity<tbWarehouse>()
.HasMany(e => e.tbWarehouseUser)
.WithRequired(e => e.tbWarehouse)
.HasForeignKey(e => e.sWarehouseName)
.WillCascadeOnDelete(false);
modelBuilder.Entity<tbWarehouseUser>()
.Property(e => e.sUserName)
.IsFixedLength()
.IsUnicode(false);
modelBuilder.Entity<tbWarehouseUser>()
.Property(e => e.sWarehouseName)
.IsFixedLength()
.IsUnicode(false);
modelBuilder.Entity<tbWarehouseUser>()
.Property(e => e.sUserPass)
.IsFixedLength()
.IsUnicode(false);
}
}

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

EF Code First - Invalid column name

Im getting an error "Invalid column name 'FeeLevel_LevelId' which makes absolutely no sense considering all properties are simple types and there is no FeeLevel nor a LevelId object in this object.
So my context is:
public partial class FeesDbContext : DisconnectedEntityContext
{
public DbSet<Currency> Currencies { get; set; }
public DbSet<FeeLevel> FeeLevels { get; set; }
public DbSet<FeeLevelDetail> FeeLevelDetails { get; set; }
public DbSet<FeeType> FeeTypes { get; set; }
public DbSet<MemberFeeDiscountLevel> MemberFeeDiscountLevels { get; set; }
public FeesDbContext()
: base("FeesDb") { }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new FeeLevelMap());
modelBuilder.Configurations.Add(new FeeLevelDetailMap());
modelBuilder.Configurations.Add(new FeeTypeMap());
modelBuilder.Configurations.Add(new CurrencyMap());
modelBuilder.Configurations.Add(new MemberFeeDiscountLevelMap());
}
public static void ApplyChanges<TEntity>(TEntity root)
where TEntity : class, IObjectWithState
{
using (var context = new FeesDbContext())
{
context.Set<TEntity>().Add(root);
foreach (var entry in context.ChangeTracker.Entries<IObjectWithState>())
{
IObjectWithState stateInfo = entry.Entity;
entry.State = ConvertState(stateInfo.State);
}
context.SaveChanges();
}
}
}
The POCO is:
public partial class MemberFeeDiscountLevel : AbstractState
{
public long MemberFeeDiscountLevelId { get; set; }
public System.Guid MemberId { get; set; }
public short MemberAsType { get; set; }
public long FeeDiscountLevelId { get; set; }
public System.DateTime FeeDiscountLevelAppliedDate { get; set; }
public Nullable<System.DateTime> FeeDiscountLevelExpiresDate { get; set; }
public Nullable<long> FallbackFeeDiscountLevelId { get; set; }
public System.Guid UserId { get; set; }
public System.DateTime LastModified { get; set; }
public MemberFeeDiscountLevel(ObjectState state) : base(state) { }
public MemberFeeDiscountLevel()
{
}
}
It's mapping is:
public class MemberFeeDiscountLevelMap : EntityTypeConfiguration<MemberFeeDiscountLevel>
{
public MemberFeeDiscountLevelMap()
{
// Primary Key
this.HasKey(t => t.MemberFeeDiscountLevelId);
this.Ignore(t => t.State);
// Properties
// Table & Column Mappings
this.ToTable("MemberFeeDiscountLevel");
this.Property(t => t.MemberFeeDiscountLevelId).HasColumnName("MemberFeeDiscountLevelId");
this.Property(t => t.MemberId).HasColumnName("MemberId");
this.Property(t => t.MemberAsType).HasColumnName("MemberAsType");
this.Property(t => t.FeeDiscountLevelId).HasColumnName("FeeDiscountLevelId");
this.Property(t => t.FeeDiscountLevelAppliedDate).HasColumnName("FeeDiscountLevelAppliedDate");
this.Property(t => t.FeeDiscountLevelExpiresDate).HasColumnName("FeeDiscountLevelExpiresDate");
this.Property(t => t.FallbackFeeDiscountLevelId).HasColumnName("FallbackFeeDiscountLevelId");
this.Property(t => t.UserId).HasColumnName("UserId");
this.Property(t => t.LastModified).HasColumnName("LastModified");
}
}
The database table is:
and it has not relationships. Yet EF is generating the following SQL:
exec sp_executesql N'INSERT [dbo].[MemberFeeDiscountLevel]([MemberId], [MemberAsType], [FeeDiscountLevelId], [FeeDiscountLevelAppliedDate], [FeeDiscountLevelExpiresDate], [FallbackFeeDiscountLevelId], [UserId], [LastModified], [FeeLevel_LevelId])
VALUES (#0, #1, #2, #3, #4, #5, #6, #7, #8, NULL)
SELECT [MemberFeeDiscountLevelId]
FROM [dbo].[MemberFeeDiscountLevel]
WHERE ##ROWCOUNT > 0 AND [MemberFeeDiscountLevelId] = scope_identity()',N'#0 uniqueidentifier,#1 smallint,#2 bigint,#3 datetime2(7),#4 datetime2(7),#5 bigint,#6 uniqueidentifier,#7 datetime2(7),#8 int',#0='DAF771D1-079F-4743-B5C7-FD0FA1C63E19',#1=0,#2=1012,#3='2014-01-24 12:05:36.0608347',#4='2014-02-01 00:00:00',#5=1018,#6='EEDF2C83-2123-4B1C-BF8D-BE2D2FA26D09',#7='2014-01-24 12:05:36.0608347'
go
UPDATE:
Creating a new Fees2DbContext stripping out the other DbSets "fixes" the problem.... but I dont know why... none of these classes / sets are related to the class in question.
public partial class Fees2DbContext : DisconnectedEntityContext
{
public DbSet<MemberFeeDiscountLevel> MemberFeeDiscountLevels { get; set; }
public Fees2DbContext()
: base("FeesDb") { }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new MemberFeeDiscountLevelMap());
}
public static void ApplyChanges<TEntity>(TEntity root)
where TEntity : class, IObjectWithState
{
using (var context = new Fees2DbContext())
{
context.Set<TEntity>().Add(root);
foreach (var entry in context.ChangeTracker.Entries<IObjectWithState>())
{
IObjectWithState stateInfo = entry.Entity;
entry.State = ConvertState(stateInfo.State);
}
context.SaveChanges();
}
}
}
UPDATE 2:
public partial class FeeLevel : AbstractState
{
public FeeLevel()
{
this.FeeLevelDetails = new List<FeeLevelDetail>();
this.MemberFeeDiscountLevels = new List<MemberFeeDiscountLevel>();
}
public long LevelId { get; set; }
public string LevelName { get; set; }
public int CurrencyId { get; set; }
public System.DateTime LastModified { get; set; }
public bool IsSystemOwned { get; set; }
public System.Guid UserId { get; set; }
public virtual Currency Currency { get; set; }
[ScriptIgnore]
public virtual ICollection<FeeLevelDetail> FeeLevelDetails { get; set; }
public virtual ICollection<MemberFeeDiscountLevel> MemberFeeDiscountLevels { get; set; }
}
public class FeeLevelMap : EntityTypeConfiguration<FeeLevel>
{
public FeeLevelMap()
{
// Primary Key
this.HasKey(t => t.LevelId);
this.Ignore(t => t.State);
// Properties
this.Property(t => t.LevelId);
// .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
this.Property(t => t.LevelName)
.IsRequired()
.HasMaxLength(50);
// Table & Column Mappings
this.ToTable("FeeLevel");
this.Property(t => t.LevelId).HasColumnName("LevelId");
this.Property(t => t.LevelName).HasColumnName("LevelName");
this.Property(t => t.CurrencyId).HasColumnName("CurrencyId");
this.Property(t => t.LastModified).HasColumnName("LastModified");
this.Property(t => t.UserId).HasColumnName("UserId");
// Relationships
this.HasRequired(t => t.Currency)
.WithMany(t => t.FeeLevels)
.HasForeignKey(d => d.CurrencyId);
}
}
FeeLevel.MemberFeeDiscountLevels is a navigation property and it introduces a one-to-many relationship between FeeLevel and MemberFeeDiscountLevel: A FeeLevel can have many MemberFeeDiscountLevels which means at the same time that a MemberFeeDiscountLevel has a single FeeLevel. Although you don't have a navigation and foreign key property in MemberFeeDiscountLevel the database must have a foreign key in the MemberFeeDiscountLevel table in order to model this relationship. EF assumes a default FK name as "related entity name+underscore+primary key name" = FeeLevel_LevelId. Because your database table doesn't have this column you get the exception.

Resources