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 ?
Related
I searched a lot but no luck to find a solution to my entities.
I have 2 entities. Device & PersonEnterExit
I have 2 Collection of PersonEnterExit in Device entity.
When I run database update it says me you have same entity with different name. do manually name them. how do i do that ? I want to do this with fluent api in onModelCreating.
Devices.cs
using System;
using System.Collections.Generic;
namespace DesTech.Core.Entities
{
public class Device : BaseEntity
{
public bool? IsConnected { get; set; }
public string Name { get; set; }
public string Ip { get; set; }
public int Port { get; set; }
public DateTime? LastConnectTime { get; set; }
public DateTime? ChangeClockBatteryWarningTime { get; set; }
public bool HasFp { get; set; }
public virtual Location Location { get; set; }
public virtual ICollection<DeviceOptLog> DeviceOptLog { get; set; }
public virtual ICollection<DevicePerson> DevicePerson { get; set; }
public virtual ICollection<DeviceTimeZone> DeviceTimeZone { get; set; }
public virtual ICollection<PersonEnterExit> PersonEnterExitEnDevice { get; set; }
public virtual ICollection<PersonEnterExit> PersonEnterExitExDevice { get; set; }
public virtual ICollection<PersonPassLog> PersonPassLog { get; set; }
}
}
PersonEnterExit.cs
using System;
namespace DesTech.Core.Entities
{
public class PersonEnterExit : BaseEntity
{
public int Type { get; set; }
public int? PersonId { get; set; }
public DateTime? NoEnterTime { get; set; }
public int? EnDeviceId { get; set; }
public DateTime? EnVerifyDate { get; set; }
public string EnPlate { get; set; }
public int? ExDeviceId { get; set; }
public DateTime? ExVerifyDate { get; set; }
public virtual Device EnDevice { get; set; }
public virtual Device ExDevice { get; set; }
public virtual Person Person { get; set; }
}
}
You can use one of these
FluentApi
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Device>()
.HasMany(a => a.PersonEnterExitEnDevice)
.WithOne(a => a.EnDevice)
.HasForeignKey(a => a.EnDeviceId).OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<Device>()
.HasMany(a => a.PersonEnterExitExDevice)
.WithOne(a => a.ExDevice)
.HasForeignKey(a => a.ExDeviceId).OnDelete(DeleteBehavior.Restrict);
}
Metadata. you can use InverseProperty to define the relationships.
namespace DesTech.Core.Entities
{
public class PersonEnterExit : BaseEntity
{
public int Type { get; set; }
public int? PersonId { get; set; }
public DateTime? NoEnterTime { get; set; }
public int? EnDeviceId { get; set; }
public DateTime? EnVerifyDate { get; set; }
public string EnPlate { get; set; }
public int? ExDeviceId { get; set; }
public DateTime? ExVerifyDate { get; set; }
[InverseProperty("PersonEnterExitEnDevice")]
public virtual Device EnDevice { get; set; }
[InverseProperty("PersonEnterExitExDevice")]
public virtual Device ExDevice { get; set; }
public virtual Person Person { get; set; }
}
}
namespace DesTech.Core.Entities
{
public class Device : BaseEntity
{
public bool? IsConnected { get; set; }
public string Name { get; set; }
public string Ip { get; set; }
public int Port { get; set; }
public DateTime? LastConnectTime { get; set; }
public DateTime? ChangeClockBatteryWarningTime { get; set; }
public bool HasFp { get; set; }
public virtual Location Location { get; set; }
public virtual ICollection<DeviceOptLog> DeviceOptLog { get; set; }
public virtual ICollection<DevicePerson> DevicePerson { get; set; }
public virtual ICollection<DeviceTimeZone> DeviceTimeZone { get; set; }
[InverseProperty("EnDevice")]
public virtual ICollection<PersonEnterExit> PersonEnterExitEnDevice { get; set; }
[InverseProperty("ExDevice")]
public virtual ICollection<PersonEnterExit> PersonEnterExitExDevice { get; set; }
public virtual ICollection<PersonPassLog> PersonPassLog { get; set; }
}
}
Like you mentioned, you need to explicitly configure both relationships. Otherwise, EF will get confused.
build.Entity<PersonEnterExit>()
.HasOne(e => e.EnDevice)
.WithMany(d => d.PersonEnterExitEnDevice);
build.Entity<PersonEnterExit>()
.HasOne(e => e.ExDevice)
.WithMany(d => d.PersonEnterExitExDevice);
See if this helps. You may need to explicitly configure foreign keys if this doesn't work.
Okey I combined two answers and its works now. I reply my question for maybe others use same approach. If i mistake please warn me. But it works now.
builder.HasMany(a => a.PersonEnterExitEnDevice)
.WithOne(a => a.EnDevice)
.HasForeignKey(a => a.EnDeviceId)
.OnDelete(DeleteBehavior.Restrict);
builder.HasMany(a => a.PersonEnterExitExDevice)
.WithOne(a => a.ExDevice)
.HasForeignKey(a => a.ExDeviceId)
.OnDelete(DeleteBehavior.Restrict);
builder.HasOne(d => d.EnDevice)
.WithMany(e => e.PersonEnterExitEnDevice)
.HasForeignKey(d => d.EnDeviceId)
.HasConstraintName("FK_PersonEnterExit_DeviceEn");
builder.HasOne(d => d.EnLocation)
.WithMany(e => e.PersonEnterExitEnLocation)
.HasForeignKey(d => d.EnLocationId)
.HasConstraintName("FK_PersonEnterExit_LocationEx");
I have an entity with some optional relationships and I'm doing a GetAllIncluding(someProperties) but the navigation properties keeps in null when the GetAll is done.
All relation in the include (Cliente, ClienteFuturo) keeps in null, and always almost one of them has a value on ClienteId or ClienteFuturoId
Here is my GetAll Method:
public override Task<PagedResultDto<SolicitudPrestamoDto>> GetAll(PagedAndSortedRequest input)
{
var lista = new List<SolicitudPrestamo>();
var query = Repository.GetAllIncluding(x => x.ClienteFuturo, x => x.Cliente);
query = CreateFilteredQuery(input);
query = ApplySorting(query, input);
query = FilterHelper<SolicitudPrestamo>.FilerByProperties(input.FilterProperties, query);
lista = query
.Skip(input.SkipCount)
.Take(input.MaxResultCount)
.ToList();
var result = new PagedResultDto<SolicitudPrestamoDto>(query.Count(), ObjectMapper.Map<List<SolicitudPrestamoDto>>(lista));
return Task.FromResult(result);
}
Here is the entity relation configuration:
entidad.HasOne(e => e.Cosolicitante)
.WithMany()
.HasForeignKey(e => e.CosolicitanteId)
.HasConstraintName("ForeignKey_SolicitudPrestamo_Cosolicitante")
.OnDelete(DeleteBehavior.Restrict);
entidad.HasOne(e => e.Cliente)
.WithMany()
.HasForeignKey(e => e.ClienteId)
.HasConstraintName("ForeignKey_SolicitudPrestamo_Cliente")
.OnDelete(DeleteBehavior.Restrict);
entidad.HasOne(e => e.CosolicitanteCliente)
.WithMany()
.HasForeignKey(e => e.CosolicitanteClienteId)
.HasConstraintName("ForeignKey_SolicitudPrestamo_CosolicitanteCliente")
.OnDelete(DeleteBehavior.Restrict);
entidad.HasOne(e => e.ClienteFuturo)
.WithMany()
.HasForeignKey(e => e.ClienteFuturoId)
.HasConstraintName("ForeignKey_SolicitudPrestamo_ClienteFuturo")
.OnDelete(DeleteBehavior.Restrict);
Here is my entity:
public class SolicitudPrestamo : AuditedEntity<int>
{
public string Identificador { get; set; }
public int CantidadCuotas { get; set; }
public double Monto { get; set; }
public string FormaPago { get; set; }
public DateTime Fecha { get; set; }
public string Proposito { get; set; }
public string Referencia { get; set; }
public EstadoSolicitud Estado { get; set; }
public int SucursalId { get; set; }
public virtual Sucursal Sucursal { get; set; }
public int? ClienteId { get; set; }
public virtual Cliente Cliente { get; set; }
public int? CosolicitanteClienteId { get; set; }
public virtual Cliente CosolicitanteCliente { get; set; }
public int? ClienteFuturoId { get; set; }
public virtual ClienteFuturo ClienteFuturo { get; set; }
public int ClasificacionPrestamoId { get; set; }
public virtual ClasificacionPrestamo ClasificacionPrestamo { get; set; }
public int? OficialNegocioId { get; set; }
public virtual OficialNegocio OficialNegocio { get; set; }
public int? CobradorPrestamoId { get; set; }
public virtual CobradorPrestamo CobradorPrestamo { get; set; }
public int? CosolicitanteId { get; set; }
public virtual ClienteFuturo Cosolicitante { get; set; }
public IEnumerable<GarantiaPrestamoSolicitud> ListaGarantiaPrestamo { get; set; }
public IEnumerable<ReferenciaPrestamo> ListaReferencias { get; set; }
public List<GarantiaPrestamo> ListaGarantias { get; set; }
}
Sorry for my English.
protected override IQueryable<SolicitudPrestamo> CreateFilteredQuery(PagedAndSortedRequest input)
{
return Repository.GetAll().
WhereIf(!input.Filter.IsNullOrWhiteSpace(), x =>
x.Identificador.StartsWith(input.Filter, StringComparison.CurrentCultureIgnoreCase) ||
x.FormaPago.StartsWith(input.Filter, StringComparison.CurrentCultureIgnoreCase) ||
x.Proposito.StartsWith(input.Filter, StringComparison.CurrentCultureIgnoreCase) ||
x.Referencia.StartsWith(input.Filter, StringComparison.CurrentCultureIgnoreCase)
);
}
Thanks illia-popov the problem is that in the CreatedFilteredQuery Method I forget to do the GetAllIncluding
Thanks for help.!
I'm trying to make a simple app to try Entity Framework Core, but i a have problem with setting up relations between entities. My entities:
public class Card
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Adress { get; set; }
public DateTime DoB { get; set; }
public DateTime DoS { get; set; }
public User Portal { get; set; }
public List<Reservation> Res { get; set; }
}
public class Doctor
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Email { get; set; }
public TimeSpan Start_Working { get; set; }
public TimeSpan End_Working { get; set; }
public List<Reservation> Reservations { get; set; }
public int SpecID { get; set; }
public Spec Spec { get; set; }
}
public class Reservation
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public DateTime DoR { get; set; }
public string Info { get; set; }
public int CardID { get; set; }
public Card Card_Nav_R { get; set; }
public int DoctorID { get; set; }
public Doctor Doctor { get; set; }
}
public class Spec
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public List<Doctor> Doctors { get; set; }
}
public class User
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public int CardID { get; set; }
public Card Card { get; set; }
}
And a configuration class where i tried to set up relations:
class ApplicationContext:DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Card> Cards { get; set; }
public DbSet<Reservation> Reservations { get; set; }
public DbSet<Doctor> Doctors { get; set; }
public DbSet<Spec> Specs { get; set; }
public ApplicationContext()
{
Database.EnsureCreated();
}
protected override void OnModelCreating(ModelBuilder ModelBuilder)
{
ModelBuilder.Entity<User>().HasKey(u => u.Id);
ModelBuilder.Entity<Card>().HasKey(c => c.Id);
ModelBuilder.Entity<Doctor>().HasKey(d => d.Id);
ModelBuilder.Entity<Spec>().HasKey(s => s.Id);
ModelBuilder.Entity<Reservation>().HasKey(r => r.Id);
ModelBuilder.Entity<User>().Property(u => u.Email).IsRequired();
ModelBuilder.Entity<User>().Property(u => u.Password).IsRequired();
ModelBuilder.Entity<Card>().Property(c => c.Name).IsRequired();
ModelBuilder.Entity<Card>().Property(c => c.Surname).IsRequired();
ModelBuilder.Entity<Card>().Property(c => c.DoB).IsRequired();
ModelBuilder.Entity<Card>().Property(c => c.Adress).IsRequired();
ModelBuilder.Entity<Doctor>().Property(d => d.Name).IsRequired();
ModelBuilder.Entity<Doctor>().Property(d => d.Surname).IsRequired();
ModelBuilder.Entity<Doctor>().Property(d => d.Spec).IsRequired();
ModelBuilder.Entity<Doctor>().Property(d => d.Email).IsRequired();
ModelBuilder.Entity<Doctor>().Property(d => d.Start_Working).IsRequired();
ModelBuilder.Entity<Doctor>().Property(d => d.End_Working).IsRequired();
ModelBuilder.Entity<Reservation>().Property(r => r.Info).IsRequired();
ModelBuilder.Entity<Reservation>().Property(r => r.Card_Nav_R).IsRequired();
ModelBuilder.Entity<Reservation>().Property(r => r.Doctor).IsRequired();
ModelBuilder.Entity<Reservation>().Property(r => r.DoR).IsRequired();
ModelBuilder.Entity<Spec>().Property(s => s.Name).IsRequired();
ModelBuilder.Entity<Doctor>().HasOne<Spec>(d=>d.Spec).WithMany(s => s.Doctors).HasForeignKey(d => d.SpecID);
ModelBuilder.Entity<User>().HasOne<Card>(u => u.Card).WithOne(c => c.Portal).HasForeignKey<User>(u => u.CardID);
ModelBuilder.Entity<Reservation>().HasOne<Card>(r => r.Card_Nav_R).WithMany(c => c.Res).HasForeignKey(r => r.CardID);
ModelBuilder.Entity<Reservation>().HasOne<Doctor>(r => r.Doctor).WithMany(d => d.Reservations).HasForeignKey(r => r.DoctorID);
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=Simple_Try;Trusted_Connection=True;");
}
}
So, when i tried to add migration or add something to database i saw this error:
System.InvalidOperationException: 'The property or navigation 'Spec' cannot be added to the entity type 'Doctor' because a property or navigation with the same name already exists on entity type 'Doctor'.'
I really don't know how to fix this, i tried to use annotations instead of Fluent API, but had the same result.
The cause of the exception is the following line:
ModelBuilder.Entity<Doctor>().Property(d => d.Spec).IsRequired();
because Doctor.Spec is a navigation property
public class Doctor
{
// ...
public Spec Spec { get; set; }
}
and navigation properties cannot be configured via Property fluent API.
So simply remove that line. Whether reference navigation property is required or optional is controlled via relationship configuration. In this case
ModelBuilder.Entity<Doctor>()
.HasOne(d => d.Spec)
.WithMany(s => s.Doctors)
.HasForeignKey(d => d.SpecID)
.IsRequired(); // <--
although the IsRequired is automatically derived from the FK property type - since SpecID is non nullable, then the relationship is required.
For more info, see Required and Optional Properties and Required and Optional Relationships documentation topics.
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();
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 ?