Cannot create a relationship between Employee and StateProvince - c#

I have an initial class Employee with two properties StateOfEmployment, SecondaryStateOfEmployment of the same entity which is StateProvince.
I'm having this error:
{​​​​​​"Cannot create a relationship between 'StateProvince.Employee'
and 'Employee.SecondaryStateProvinceOfEmployment', because there
already is a relationship between 'StateProvince.Employee' and
'Employee.StateProvinceOfEmployment'. Navigation properties can only
participate in a single relationship."}​​​​​​
My class
public partial class Employee
{
public long EmployeeId { get; set; }
public string JobTitle { get; set; }
public string EmployeeCode { get; set; }
public long? CountryOfEmploymentId { get; set; }
public long? StateProvinceOfEmploymentId { get; set; }
public long? SecondaryStateProvinceOfEmploymentId { get; set; }
public string CostCenter { get; set; }
public DateTime StartEffDate { get; set; }
public DateTime CreatedTimestamp { get; set; }
public string CreatedUser { get; set; }
public DateTime UpdatedTimestamp { get; set; }
public string UpdatedUser { get; set; }
public bool IsDeleted { get; set; }
public long ClientId { get; set; }
public long PersonId { get; set; }
public string CityOfEmployment { get; set; }
public DateTime? HireDate { get; set; }
public string BusinessUnit { get; set; }
public string ManagerName { get; set; }
public string ManagerEmail { get; set; }
public long? EmploymentStatusId { get; set; }
public long? EmploymentTypeId { get; set; }
public string EmploymentTypeClientString { get; set; }
public string HomeLegalEntity { get; set; }
public bool Executive { get; set; }
public string JobLevel { get; set; }
public DateTime SysStartTime { get; set; }
public DateTime SysEndTime { get; set; }
public virtual Client Client { get; set; }
public virtual Country CountryOfEmployment { get; set; }
public virtual EmploymentStatus EmploymentStatus { get; set; }
public virtual EmploymentType EmploymentType { get; set; }
public virtual Person Person { get; set; }
public virtual StateProvince StateProvinceOfEmployment { get; set; }
public virtual StateProvince SecondaryStateProvinceOfEmployment { get; set; }
}
And my context is
modelBuilder.Entity<Employee>(entity =>
{
entity.Property(e => e.BusinessUnit).HasMaxLength(100);
entity.Property(e => e.CityOfEmployment).HasMaxLength(100);
entity.Property(e => e.CostCenter).HasMaxLength(100);
entity.Property(e => e.CreatedTimestamp).HasDefaultValueSql("(getutcdate())");
entity.Property(e => e.CreatedUser)
.IsRequired()
.HasMaxLength(100)
.HasDefaultValueSql("(suser_sname())");
entity.Property(e => e.EmployeeCode).HasMaxLength(100);
entity.Property(e => e.EmploymentTypeClientString).HasMaxLength(100);
entity.Property(e => e.HomeLegalEntity).HasMaxLength(100);
entity.Property(e => e.JobTitle).HasMaxLength(100);
entity.Property(e => e.ManagerEmail).HasMaxLength(100);
entity.Property(e => e.ManagerName).HasMaxLength(200);
entity.Property(e => e.UpdatedTimestamp).HasDefaultValueSql("(getutcdate())");
entity.Property(e => e.UpdatedUser)
.IsRequired()
.HasMaxLength(100)
.HasDefaultValueSql("(suser_sname())");
entity.HasOne(d => d.Client)
.WithMany(p => p.Employee)
.HasForeignKey(d => d.ClientId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Employee_Client");
entity.HasOne(d => d.CountryOfEmployment)
.WithMany(p => p.Employee)
.HasForeignKey(d => d.CountryOfEmploymentId)
.HasConstraintName("Fk_Employee_CountryId");
entity.HasOne(d => d.EmploymentStatus)
.WithMany(p => p.Employee)
.HasForeignKey(d => d.EmploymentStatusId)
.HasConstraintName("Fk_Employee_EmploymentStatusId");
entity.HasOne(d => d.EmploymentType)
.WithMany(p => p.Employee)
.HasForeignKey(d => d.EmploymentTypeId)
.HasConstraintName("Fk_Employee_EmploymentTypeId");
entity.HasOne(d => d.Person)
.WithMany(p => p.Employee)
.HasForeignKey(d => d.PersonId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Employee_Person");
entity.HasOne(d => d.StateProvinceOfEmployment)
.WithMany(p => p.Employee)
.HasForeignKey(d => d.StateProvinceOfEmploymentId)
.HasConstraintName("Fk_Employee_StateProvinceId");
entity.HasOne(d => d.SecondaryStateProvinceOfEmployment)
.WithMany(p => p.Employee)
.HasForeignKey(d => d.SecondaryStateProvinceOfEmploymentId)
.HasConstraintName("Fk_Employee_SecondaryStateProvinceId");
});
What am I doing wrong? Thank you.

Use DataAnnotations such as ForeignKey attribute, if you use it you don't need to add any code to the OnModelCreate method:
[Table("Employee")]
public partial class Employee
{
[Key]
public long EmployeeId { get; set; }
[Column("JobTitle")]
public string JobTitle { get; set; }
[Column("EmployeeCode")]
public string EmployeeCode { get; set; }
[Column("CountryOfEmploymentId")]
[ForeignKey("CountryOfEmployment")]
public long? CountryOfEmploymentId { get; set; }
[Column("StateProvinceOfEmploymentId")]
[ForeignKey("StateProvinceOfEmployment")]
public long? StateProvinceOfEmploymentId { get; set; }
[Column("SecondaryStateProvinceOfEmploymentId")]
[ForeignKey("SecondaryStateProvinceOfEmployment")]
public long? SecondaryStateProvinceOfEmploymentId { get; set; }
[Column("CostCenter")]
public string CostCenter { get; set; }
[Column("StartEffDate")]
public DateTime StartEffDate { get; set; }
[Column("CreatedTimestamp")]
public DateTime CreatedTimestamp { get; set; }
[Column("CreatedUser")]
public string CreatedUser { get; set; }
[Column("UpdatedTimestamp")]
public DateTime UpdatedTimestamp { get; set; }
[Column("UpdatedUser")]
public string UpdatedUser { get; set; }
[Column("IsDeleted")]
public bool IsDeleted { get; set; }
[Column("ClientId")]
public long ClientId { get; set; }
[Column("PersonId")]
public long PersonId { get; set; }
[Column("CityOfEmployment")]
public string CityOfEmployment { get; set; }
[Column("HireDate")]
public DateTime? HireDate { get; set; }
[Column("BusinessUnit")]
public string BusinessUnit { get; set; }
[Column("ManagerName")]
public string ManagerName { get; set; }
[Column("ManagerEmail")]
public string ManagerEmail { get; set; }
[Column("EmploymentStatusId")]
public long? EmploymentStatusId { get; set; }
[Column("EmploymentTypeId")]
public long? EmploymentTypeId { get; set; }
[Column("EmploymentTypeClientString")]
public string EmploymentTypeClientString { get; set; }
[Column("HomeLegalEntity")]
public string HomeLegalEntity { get; set; }
[Column("Executive")]
public bool Executive { get; set; }
[Column("JobLevel")]
public string JobLevel { get; set; }
[Column("SysStartTime")]
public DateTime SysStartTime { get; set; }
[Column("SysEndTime")]
public DateTime SysEndTime { get; set; }
[IgnoreDataMember]
public virtual Client Client { get; set; }
[IgnoreDataMember]
public virtual Country CountryOfEmployment { get; set; }
[IgnoreDataMember]
public virtual EmploymentStatus EmploymentStatus { get; set; }
[IgnoreDataMember]
public virtual EmploymentType EmploymentType { get; set; }
[IgnoreDataMember]
public virtual Person Person { get; set; }
[IgnoreDataMember]
public virtual StateProvince StateProvinceOfEmployment { get; set; }
[IgnoreDataMember]
public virtual StateProvince SecondaryStateProvinceOfEmployment { get; set; }
}

Below should work,
entity.HasOne(d => d.SecondaryStateProvinceOfEmployment)
.WithMany(p => p.Employee)
.HasForeignKey(d => d.SecondaryStateProvinceOfEmploymentId)
.HasConstraintName("Fk_Employee_SecondaryStateProvinceId").OnDelete(DeleteBehavior.Restrict);

Related

How to fix 'Unable to determine the relationship represented by navigation property' error in Entity Framework

When I try to register a user on my .NET Core 2.1 website (using identity) I get the following error:
"InvalidOperationException: Unable to determine the relationship represented by navigation property 'City.ConnectionStartCity' of type 'ICollection'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.".
The reason this happens probably has nothing to do with identity, but registering and logging in is currently the only way I know how to trigger it.
I still want the properties City en ICollection<Connection> in my classes so I don't want to use the [NotMapped] attribute.
I searched on the internet and found that this is caused by a many-many relationship, I feel like this is not the case tho.
Class Connection:
public partial class Connection
{
public Connection()
{
ConnectionRoute = new HashSet<ConnectionRoute>();
}
public int Id { get; set; }
public int StartCityId { get; set; }
public int EndCityId { get; set; }
public int AantalMinuten { get; set; }
public double Prijs { get; set; }
public Stad StartCity { get; set; }
public Stad EndCity { get; set; }
public ICollection<ConnectionRoute> ConnectionRoute{ get; set; }
}
Class City:
public partial class City
{
public City()
{
AspNetUsers = new HashSet<AspNetUsers>();
Hotel = new HashSet<Hotel>();
ConnectionStartCity = new HashSet<Connection>();
ConnectionEndCity= new HashSet<Connection>();
}
public int Id { get; set; }
public string Name { get; set; }
public string Country { get; set; }
public ICollection<AspNetUsers> AspNetUsers { get; set; }
public ICollection<Hotel> Hotel { get; set; }
public ICollection<Connection> ConnectionStartCity { get; set; }
public ICollection<Connection> ConnectionEndCity { get; set; }
}
Class treinrittenContext (dbContext) extract:
public virtual DbSet<City> City{ get; set; }
public virtual DbSet<Connection> Connection{ get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
...
modelBuilder.Entity<City>(entity =>
{
entity.Property(e => e.Country)
.IsRequired()
.HasMaxLength(255)
.IsUnicode(false);
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(255)
.IsUnicode(false);
entity.HasMany(p => p.ConnectionStartcity)
.WithOne(d => d.StartCity)
.HasForeignKey(d => d.StartCityId);
entity.HasMany(p => p.ConnectionEndCity)
.WithOne(d => d.EndCity)
.HasForeignKey(d => d.EndCityId);
});
...
modelBuilder.Entity<Connection>(entity =>
{
entity.HasOne(d => d.StartCity)
.WithMany(p => p.ConnectionStartCity)
.HasForeignKey(d => d.StartCityId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Verbinding_BeginStad");
entity.HasOne(d => d.EndCity)
.WithMany(p => p.ConnectionEndCity)
.HasForeignKey(d => d.EndCityId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Verbinding_EindStad");
});
...
}
I expect this to work (since in my eyes it's a one-many relation), but it doesn't.
UPDATE
You have multiple options here:
Option 1 with result 1
City Class becomes:
public partial class City
{
public City()
{
Connections = new HashSet<Connection>();
}
public int Id { get; set; }
public string Name { get; set; }
public string Country { get; set; }
public ICollection<Connection> Connections { get; set; }
}
Connection Class becomes:
public partial class Connection
{
public Connection()
{
}
public int Id { get; set; }
public int StartCityId { get; set; }
public int EndCityId { get; set; }
public int AantalMinuten { get; set; }
public double Prijs { get; set; }
}
Your OnModelCreating becomes:
modelBuilder.Entity<City>().HasMany(city => city.Connections)
.WithRequired().HasForeignKey(con => con.EndCityId);
modelBuilder.Entity<City>().HasMany(city => city.Connections)
.WithRequired().HasForeignKey(con => con.StartCityId);
OR you can do something like this as well wchich would be option 2 with results 2:
City Class becomes:
public partial class City
{
public City()
{
Connections = new HashSet<Connection>();
}
public int Id { get; set; }
public string Name { get; set; }
public string Country { get; set; }
public ICollection<Connection> Connections { get; set; }
}
Connection Class becomes:
public partial class Connection
{
public Connection()
{
}
public int Id { get; set; }
public virtual ICollection<City> Cities { get; set; }
public int AantalMinuten { get; set; }
public double Prijs { get; set; }
}
And you don't have to do anything in your OnModelCreating.
In my case, problem occurred because when of overriding OnModelCreating in DbContext and not calling base.OnModelCreating(builder).

Violation of PRIMARY KEY constraint, even though im not adding or modyfying anything in the context

My program is parsing an xml file and adding orders from this file to the mssql database. Before he adds those orders to database he analyses them if there are any duplicates that need to be dealt with.
foreach (var newOrderXml in newOrdersList)
{
var dupesInDb = _context.OrdersXml.Include(o=>o.OrderXmlItems)
.Where(o => o.OrX_ORDERNR.Contains(newOrderXml.OrX_ORDERNR))
.ToList();
_context.SaveChanges();
}
Program loops through all of the new orders in newOrderList and gets the list of duplicates with linq query. If there are 0 duplicates and nothing gets returned, everything works fine, but if a single duplicate is returned then SaveChanges method will throw an exception "Violation of PRIMARY KEY constraint PK_dbo.SewingCardBundles, Cannot insert duplicate key in object 'dbo.SewingCardBundles'. The duplicate key value is (1).", even though im not adding or modyfying anything in the context. I dont really know what is happening, all im doing is getting, im not changing anything, im not creating new objects. This exception happens exactly at this spot, if i try to save changes before this linq query then nothing bad happens but if i try it after this linq query i get the exceptions. So where does those changes to context come from?
Here are my models:
public class OrderXml
{
public OrderXml()
{
OrderXmlItems = new List<OrderXmlItem>();
}
public int OrX_Id { get; set; }
public string OrX_ORDERNR { get; set; }
public string OrX_REFERGB { get; set; }
public int? OrX_CUSTOMERNUM { get; set; }
public string OrX_DNAME { get; set; }
public string OrX_DADR { get; set; }
public string OrX_DPCODE { get; set; }
public string OrX_POSTALCODE { get; set; }
public string OrX_COUNTRY { get; set; }
public string OrX_PHONE { get; set; }
public string OrX_EMAIL { get; set; }
public int? OrX_LANG { get; set; }
public int? OrX_CUSTGRP { get; set; }
public int? OrX_QUALITCON { get; set; }
public string OrX_SHIPVIA { get; set; }
public string OrX_DATE1 { get; set; }
public string OrX_DATE2 { get; set; }
public string OrX_DELIVGB { get; set; }
public string OrX_SORT { get; set; }
public int? OrX_CURLAB { get; set; }
public List<OrderXmlItem> OrderXmlItems { get; set; }
public Adress Adress { get; set; }
}
public OrderXmlItem()
{
SewingCardBundle = new SewingCardBundle();
}
public int OxI_Id { get; set; }
public int? OxI_PRODUCT { get; set; }
public int? OxI_ORDERLINE { get; set; }
public int? OxI_QUANTITY { get; set; }
public int? OxI_TYPE { get; set; }
public string OxI_TPFABNR { get; set; }
public string OxI_TPFABDEF { get; set; }
public string OxI_TPFABNAME { get; set; }
public int? OxI_CURDIR { get; set; }
public int? OxI_CURWIDTH { get; set; }
public int? OxI_CURHEIGHT { get; set; }
public int? OxI_WORKMETH { get; set; }
public int? OxI_FOLDTYPE { get; set; }
public decimal? OxI_FOLDFACT { get; set; }
public int? OxI_CURBAND { get; set; }
public int? OxI_CURHEAD { get; set; }
public int? OxI_CURBOTSEAM { get; set; }
public int? OxI_PACKWLEFT { get; set; }
public int? OxI_PACKWRIGHT { get; set; }
public decimal? OxI_NRSTROL { get; set; }
public decimal? OxI_NRSTROR { get; set; }
public int? OxI_LINTYP { get; set; }
public string OxI_LINCOL { get; set; }
public int? OxI_EMBSORT { get; set; }
public int? OxI_EXTRA { get; set; }
public int? OxI_PRODUCE { get; set; }
public int? OxI_PACKSORT { get; set; }
public int? OxI_CURMODEL { get; set; }
public string OxI_BARCODE { get; set; }
public string OxI_EXTRAINF { get; set; }
public int? OxI_RAILTYP { get; set; }
public int? OxI_RAILCONT { get; set; }
public int? OxI_RAILCONTSIDE { get; set; }
public decimal? OxI_FABSTROTOT { get; set; }
public decimal? OxI_FABSTROLEFT { get; set; }
public decimal? OxI_FABSTRORIGHT { get; set; }
public int? OxI_FABUNDSIZ { get; set; }
public int? OxI_FABTOTSIZ { get; set; }
public int? OxI_LINSTROTOT { get; set; }
public int? OxI_LINUNDSIZ { get; set; }
public int? OxI_LINTOTSIZ { get; set; }
public decimal? OxI_FABWIDTH { get; set; }
public int? OxI_CHILDSFT { get; set; }
public int? OxI_FOLDSORT { get; set; }
public int? OxI_EMBLENGTH { get; set; }
public int? OxI_PACKMETH { get; set; }
public int OrderXmlId { get; set; }
public OrderXml OrderXml { get; set; }
public SewingCardBundle SewingCardBundle { get; set; }
}
public class SewingCardBundle
{
public SewingCardBundle()
{
FlamanSewingCards = new List<FlamandzkaSewingCard>();
FlamandzkaBrytaSewingCards = new List<FlamandzkaBrytaSewingCard>();
OczkaSewingCards = new List<OczkaSewingCard>();
OczkaBrytaSewingCards = new List<OczkaBrytaSewingCard>();
WellenbandSewingCards = new List<WellenbandSewingCard>();
WellenbandBrytaSewingCards = new List<WellenbandBrytaSewingCard>();
PodwiazkaSewingCards = new List<PodwiazkaSewingCard>();
TunelSewingCards = new List<TunelSewingCard>();
}
public int SwC_Id { get; set; }
public OrderXmlItem OrderXmlItem { get; set; }
public List<FlamandzkaSewingCard> FlamanSewingCards { get; set; }
public List<FlamandzkaBrytaSewingCard> FlamandzkaBrytaSewingCards { get; set; }
public List<OczkaSewingCard> OczkaSewingCards { get; set; }
public List<OczkaBrytaSewingCard> OczkaBrytaSewingCards { get; set; }
public List<WellenbandSewingCard> WellenbandSewingCards { get; set; }
public List<WellenbandBrytaSewingCard> WellenbandBrytaSewingCards { get; set; }
public List<PodwiazkaSewingCard> PodwiazkaSewingCards { get; set; }
public List<TunelSewingCard> TunelSewingCards { get; set; }
}
and my Fluent API configurations for those models:
public class OrderXmlConfiguration : EntityTypeConfiguration<OrderXml>
{
public OrderXmlConfiguration()
{
HasKey(o => o.OrX_Id);
Property(o => o.OrX_ORDERNR).IsRequired();
Property(o => o.OrX_REFERGB).IsRequired();
Property(o => o.OrX_CUSTOMERNUM).IsRequired();
Property(o => o.OrX_DNAME).IsRequired();
Property(o => o.OrX_DPCODE).IsRequired();
Property(o => o.OrX_POSTALCODE).IsRequired();
Property(o => o.OrX_COUNTRY).IsRequired();
Property(o => o.OrX_LANG).IsRequired();
Property(o => o.OrX_CUSTGRP).IsRequired();
Property(o => o.OrX_SHIPVIA).IsRequired();
Property(o => o.OrX_CURLAB).IsRequired();
HasMany(i => i.OrderXmlItems)
.WithRequired(o => o.OrderXml)
.HasForeignKey(o => o.OrderXmlId)
.WillCascadeOnDelete(true);
}
}
public class OrderXmlItemConfiguration : EntityTypeConfiguration<OrderXmlItem>
{
public OrderXmlItemConfiguration()
{
HasKey(o => o.OxI_Id);
Property(p => p.OxI_Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(p => p.OxI_PRODUCT).IsRequired();
Property(p => p.OxI_ORDERLINE).IsRequired();
Property(p => p.OxI_QUANTITY).IsRequired();
Property(p => p.OxI_TYPE).IsRequired();
Property(p => p.OxI_CURDIR).IsRequired();
Property(p => p.OxI_CURWIDTH).IsRequired();
Property(p => p.OxI_CURHEIGHT).IsRequired();
Property(p => p.OxI_WORKMETH).IsRequired();
Property(p => p.OxI_FOLDTYPE).IsRequired();
Property(p => p.OxI_FOLDFACT).IsRequired();
Property(p => p.OxI_PACKWLEFT).IsRequired();
Property(p => p.OxI_PACKWRIGHT).IsRequired();
Property(p => p.OxI_BARCODE).IsRequired();
HasRequired(i => i.SewingCardBundle)
.WithRequiredPrincipal( s=> s.OrderXmlItem)
.WillCascadeOnDelete(true);
}
}
public class SewingCardBundleConfiguration : EntityTypeConfiguration<SewingCardBundle>
{
public SewingCardBundleConfiguration()
{
HasKey(s => s.SwC_Id);
HasMany(s=>s.FlamanSewingCards)
.WithRequired(c=>c.SewingCardBundle)
.WillCascadeOnDelete(true);
HasMany(s => s.FlamandzkaBrytaSewingCards)
.WithRequired(c => c.SewingCardBundle)
.WillCascadeOnDelete(true);
HasMany(s => s.OczkaBrytaSewingCards)
.WithRequired(c => c.SewingCardBundle)
.WillCascadeOnDelete(true);
HasMany(s => s.OczkaSewingCards)
.WithRequired(c => c.SewingCardBundle)
.WillCascadeOnDelete(true);
HasMany(s => s.WellenbandSewingCards)
.WithRequired(c => c.SewingCardBundle)
.WillCascadeOnDelete(true);
HasMany(s => s.WellenbandBrytaSewingCards)
.WithRequired(c => c.SewingCardBundle)
.WillCascadeOnDelete(true);
HasMany(s => s.TunelSewingCards)
.WithRequired(c => c.SewingCardBundle)
.WillCascadeOnDelete(true);
HasMany(s => s.PodwiazkaSewingCards)
.WithRequired(c => c.SewingCardBundle)
.WillCascadeOnDelete(true);
}
}
I'm not sure why you are calling SaveChanges in the first place (it is not needed), but once you get your data from database, context will track them (i.e. have them cached).
Since, you haven't specified AsNoTracking in your query, SaveChanges method will try to save entities which are being tracked which will lead to your "primary key violation" exception.
To circumvent the issue, you can just specify AsNoTracking:
var dupesInDb = _context
.OrdersXml.Include(o=>o.OrderXmlItems)
.Where(o => o.OrX_ORDERNR.Contains(newOrderXml.OrX_ORDERNR))
.AsNoTracking()
.ToList();

Mapping to nested value Automapper

I'm struggling to map 2 objects. Basically have Product which is my EF model, and I'm mapping this to ProductDto, which has FileDto.
I'd like to map Product.FileName to ProductDto.File.Internal name, how to do this?
Classes below.
public class Product : BaseEntity<long>
{
[MaxLength(100)]
public string Name { get; set; }
[MaxLength(100)]
public string Barcode { get; set; }
public int ShelfLife { get; set; }
public int Weight { get; set; }
public bool HasAllergens { get; set; }
[MaxLength(100)]
public string FileName { get; set; }
[ForeignKey("Id")]
public int CustomerId { get; set; }
public virtual ICollection<ProductIngredient> ProductIngredient { get; set; }
public virtual ICollection<Nutrition> Nutritions { get; set; }
public virtual ICollection<ProductComposition> Composition { get; set; }
public virtual IList<ProductionProcess> ProductionProcess { get; set; }
}
public class ProductDto
{
public long Id { get; set; }
public DateTime CretedOn { get; set; }
public DateTime UpdatedOn { get; set; }
public string Name { get; set; }
public string Barcode { get; set; }
public int ShelfLife { get; set; }
public int Weight { get; set; }
public bool HasAllergens { get; set; }
public int CustomerId { get; set; }
public FileDto File { get; set; }
public IList<IngredientDto> Ingredients { get; set; }
public IList<NutritionDto> Nutritions { get; set; }
public IList<ProductCompositionDto> Composition { get; set; }
public IList<ProductionProcessDto> ProductionProcess { get; set; }
}
public class ProductionProcessDto
{
public string Key { get; set; }
public string Value { get; set; }
public FileDto File { get; set; }
}
public class NutritionDto
{
public string Key { get; set; }
public string Value { get; set; }
}
public class ProductCompositionDto
{
public string Key { get; set; }
public string Value { get; set; }
}
File Dto:
public class FileDto
{
public string Base64EncodedFile { get; set; }
public string OriginalName { get; set; }
public string InternalName { get; set; }
public string Type { get; set; }
}
Automapper so far:
//Product
CreateMap<Nutrition, NutritionDto>().ReverseMap();
CreateMap<ProductComposition, ProductCompositionDto>().ReverseMap();
CreateMap<ProductionProcessDto, ProductionProcess>()
.ForMember(dest => dest.FileInternalName, opt => opt.MapFrom(src => src.File.InternalName))
.ForMember(dest => dest.FileOriginalName, opt => opt.MapFrom(src => src.File.OriginalName))
.ReverseMap();
CreateMap<Product, ProductDto>()
.ForMember(d => d.File, o => o.MapFrom(s => Mapper.Map<Product, FileDto>(s)))
.ForMember(d => d.Nutritions, o => o.MapFrom(s => s.Nutritions))
.ForMember(d => d.Composition, o => o.MapFrom(s => s.Composition))
.ForMember(d => d.ProductionProcess, o => o.MapFrom(s => s.ProductionProcess))
.ForMember(d => d.Ingredients, o => o.MapFrom(s => s.ProductIngredient.Select(pi => pi.Ingredients)))
.ReverseMap();
CreateMap<ProductDto, Product>()
.ForMember(d => d.FileName, o => o.MapFrom(s => s.File.InternalName))
.ReverseMap();
I am able to map from ProductDto (on data post) to Product but not other way around, all help much appreciated
Thanks
This code solved my issue:
.ForMember(d => d.File, o => o.MapFrom(model => new FileDto { InternalName = model.FileName }))
Applied to:
CreateMap<Product, ProductDto>()

WebService(asmx) serialize issue with related objects

I'm using EF codefirst with existing database in my webservice projects. I have User object.
public partial class User
{
public string Id { get; set; }
public string Email { get; set; }
public bool EmailConfirmed { get; set; }
public string PasswordHash { get; set; }
public string SecurityStamp { get; set; }
public string PhoneNumber { get; set; }
public bool PhoneNumberConfirmed { get; set; }
public bool TwoFactorEnabled { get; set; }
public DateTime? LockoutEndDateUtc { get; set; }
public bool LockoutEnabled { get; set; }
public int AccessFailedCount { get; set; }
public string UserName { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public DateTime? BirthDay { get; set; }
public int? BirthPlace { get; set; }
public string Discriminator { get; set; }
public int? TeamId { get; set; }
public int? AvatarId { get; set; }
public DateTime? RegisterationDate { get; set; }
public DateTime? CodeSendDate { get; set; }
public string ActivationCode { get; set; }
public string PasswordResetToken { get; set; }
public string FacebookAvatar { get; set; }
public string FacebookId { get; set; }
public bool? UseFacebookAvatar { get; set; }
public string Address { get; set; }
public string IpAddress { get; set; }
public bool? SmsCheck { get; set; }
[XmlIgnore]
public virtual Avatar Avatar { get; set; }
[XmlIgnore]
public virtual ICollection<CouponApplicationUser> CouponApplicationUsers { get; set; }
[XmlIgnore]
public virtual ICollection<Coupon> Coupons { get; set; }
[XmlIgnore]
public virtual ICollection<UserClaim> UserClaims { get; set; }
[XmlIgnore]
public virtual ICollection<UserLogin> UserLogins { get; set; }
[XmlIgnore]
public virtual ICollection<UserRole> UserRoles { get; set; }
}
Here is my object relations :
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Avatar>()
.HasMany(e => e.Users)
.WithOptional(e => e.Avatar)
.WillCascadeOnDelete();
modelBuilder.Entity<User>()
.HasMany(e => e.CouponApplicationUsers)
.WithRequired(e => e.User)
.HasForeignKey(e => e.ApplicationUser_Id);
modelBuilder.Entity<User>()
.HasMany(e => e.UserClaims)
.WithOptional(e => e.User)
.HasForeignKey(e => e.IdentityUser_Id);
modelBuilder.Entity<User>()
.HasMany(e => e.UserLogins)
.WithOptional(e => e.User)
.HasForeignKey(e => e.IdentityUser_Id);
modelBuilder.Entity<User>()
.HasMany(e => e.UserRoles)
.WithOptional(e => e.User)
.HasForeignKey(e => e.IdentityUser_Id);
}
Member.asmx :
[WebMethod]
public User GetUser(string userId)
{
using (var context = new MemberContext())
{
var user = context.Users.FirstOrDefault(u => u.Id == userId);
return user;
}
}
I m getting error while seriazlie on runtime.
"System.InvalidOperationException: There was an error generating the XML document. ---> System.InvalidOperationException: The type System.Data.Entity.DynamicProxies.User_43DB1D255133CC8990A023D6D7354697C201107F7F44D46786E12943B0163999 was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically."
Its about related objects which have [XmlIgnore]
I tried to remove relations and it worked.
What is the solution to ignore these properties on serialize ?

EF 5, Fluent API : invalid column name "Source_ID"

Good morning
I Get invalid column name "Source_ID". my models are :
product:
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public Nullable<decimal> PreviousPrice { get; set; }
public string Url { get; set; }
public int SourceID { get; set; }
public int SectionID { get; set; }
public int CategoryID { get; set; }
public Nullable<int> BrandID { get; set; }
public string PublisherProductID { get; set; }
public string PictureFilename { get; set; }
public bool Deleted { get; set; }
public Nullable<int> Score { get; set; }
public string EAN { get; set; }
public string ExtraAttributes { get; set; }
public DateTime LastUpdateDate { get; set; }
public DateTime InsertDate { get; set; }
public string Keywords { get; set; }
public virtual ProductPicture ProductPicture { get; set; }
public virtual Brand Brand { get; set; }
public virtual Source Source { get; set; }
public virtual Category Category { get; set; }
public virtual Section Section { get; set; }
public virtual ICollection<ProductComment> Comments { get; set; }
public virtual ICollection<Like> Likes { get; set; }
public virtual ICollection<Aside> Asides { get; set; }
public virtual ICollection<Wish> Wishlists { get; set; }
public virtual ICollection<UserRecommendation> UserRecommendations { get; set; }
public virtual ICollection<ProductColor> ProductColors { get; set; }
public virtual ICollection<ProductView> ProductViews { get; set; }
public virtual ICollection<PointLog> PointLogs { get; set; }
public virtual ICollection<InvitationLog> InvitationLogs { get; set; }
public virtual ICollection<FeedItem> FeedItems { get; set; }
public virtual ICollection<Sale> Sales { get; set; }
public virtual ICollection<ListProduct> ListProducts { get; set; }
public virtual ICollection<BonusMalus> BonusMalus { get; set; }
public virtual ICollection<ProductHunter> Hunters { get; set; }
Product Mapping :
HasKey(e => e.ID);
Property(e => e.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(e => e.Name).IsRequired().HasColumnType("VARCHAR").HasMaxLength(200);
Property(e => e.Description).HasColumnType("VARCHAR").HasMaxLength(4000);
Property(e => e.Price).IsRequired().HasColumnType("Money");
Property(e => e.PreviousPrice).IsOptional().HasColumnType("Money");
Property(e => e.ExtraAttributes).HasColumnType("VARCHAR").IsOptional().HasMaxLength(1000);
Property(e => e.Url).IsRequired().HasColumnType("VARCHAR").HasMaxLength(2048);
Property(e => e.LastUpdateDate).IsOptional();
Property(e => e.InsertDate).IsOptional();
Property(e => e.PictureFilename).HasColumnType("VARCHAR").HasMaxLength(200);
Property(e => e.Deleted).IsRequired();
Property(e => e.EAN).IsOptional().HasColumnType("VARCHAR").HasMaxLength(18);
Property(e => e.PublisherProductID).IsRequired().HasColumnType("VARCHAR").HasMaxLength(100);
Property(e => e.BrandID).IsOptional();
Property(e => e.SourceID).IsRequired();
Property(e => e.Keywords).HasColumnType("VARCHAR").HasMaxLength(500);
ToTable("Products");
HasOptional(t => t.Brand).WithMany(t => t.Products).HasForeignKey(d => d.BrandID);
HasRequired(e => e.Source).WithMany(s => s.Products).HasForeignKey(e => e.SourceID);
HasRequired(e => e.Category).WithMany(c => c.Products).HasForeignKey(e => e.CategoryID);
HasRequired(t => t.Section).WithMany(t => t.Products).HasForeignKey(d => d.SectionID);
Source :
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<Product> Products { get; set; }
public virtual ICollection<SourceCategory> SourceCategories { get; set; }
public virtual ICollection<SourceCategoryRule> SourceCategoryRules { get; set; }
public virtual ICollection<WishlistGame> WishlistGames { get; set; }
public virtual ICollection<SourceWebsiteCommission> Commissions { get; set; }
public virtual ICollection<Sale> Sales { get; set; }
Source Mapping :
HasKey(e => e.ID);
Property(e => e.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
Property(e => e.Name).IsRequired().HasColumnType("VARCHAR").HasMaxLength(50);
ToTable("Sources");
The tables Products & Sources are already created. when i run my solution i got this problem (invalid column name Source_ID). maybe it is an error in my mapping. Anyone have a solution ?

Categories