GetAllIncluding With Optional Relationships ABP - c#

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.!

Related

EF Core many to many of same object get error

My situation is that I have a system which contain invoices and for each invoice I can create a receipt.
The relationship is many to many because I can produce a few receipts for each invoice, and also when I create the receipt I can relate it to few invoices.
I have the following two classes: Document which represent the invoice or receipt, and DocumentOffset which associates between the documents.
public class Document
{
public Document()
{
}
public int ID { get; set; }
public string Reference { get; set; }
[Required]
public int? DocumentKind { get; set; }
[Required]
public long DocumentNum { get; set; }
[Required]
public DateTime? CreateDate { get; set; }
[Required]
public int? EntityID { get; set; }
public double TaxDeduction { get; set; }
public int Amount { get; set; }
public double SumBeforeDiscount
{
get
{
return Document2List.Sum(x => x.Sum);
}
}
public double DiscountPercent { get; set; }
public double DiscountValue
{
get
{
return SumBeforeDiscount * DiscountPercent / 100;
}
}
public double SumBeforeTax
{
get
{
return SumBeforeDiscount - DiscountValue;
}
}
public int TaxPercent { get; set; } = 17;
public double TaxValue
{
get
{
return SumBeforeTax * TaxPercent / 100;
}
}
public double Sum
{
get
{
if(DocumentKind == (int)Enums.DocumentKind.eDocumentKind.Reciept || DocumentKind == (int)Enums.DocumentKind.eDocumentKind.SupplierReciept)
{
return Document3List.Sum(x => x.Sum).Value;
}
return SumBeforeTax + TaxValue;
}
}
public double Paid
{
get
{
return Document3List.Where(x => x.Sum.HasValue).Sum(x => x.Sum.Value);
}
}
public double Balance
{
get
{
return Sum - Paid;
}
}
[Required]
public string Details { get; set; }
[Required]
public DateTime? Expire { get; set; }
public string VehicleID { get; set; }
public List<Document2> Document2List { get; set; } = new List<Document2>(); // Document items
public List<Document3> Document3List { get; set; } = new List<Document3>(); // Document payments when invoice and receipt produced in the same document
public Entity Entity { get; set; }
public ICollection<DocumentOffset> DocumentOffsets { get; set; } //this property
}
and
public class DocumentOffset
{
public int DocumentID { get; set; } //FK
public Document Document { get; set; }
public int RelatedDocumentID { get; set; } //FK
public Document RelatedDocument { get; set; }
public double Sum { get; set; }
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<MissionCardWorker>().HasKey(x => new { x.MissionCardId, x.WorkerId });
modelBuilder.Entity<MissionCardItems>().HasKey(x => new { x.MissionCardId, x.ItemId });
modelBuilder.Entity<MissionCardMission>().HasKey(x => new { x.MissionCardId, x.MissionId });
modelBuilder.Entity<DocumentOffset>()
.HasOne(x => x.Document)
.WithMany(x => x.DocumentOffsets)
.HasForeignKey(x => x.RelatedDocumentID);
modelBuilder.Entity<DocumentOffset>()
.HasOne(x => x.RelatedDocument)
.WithMany(x => x.DocumentOffsets)
.HasForeignKey(x => x.DocumentID);
}
When I try to add a migration I get the following error :
Cannot create a relationship between 'Document.DocumentOffsets' and 'DocumentOffset.RelatedDocument', because there already is a relationship between 'Document.DocumentOffsets' and 'DocumentOffset.Document'. Navigation properties can only participate in a single relationship.
What should I do resolve that?
Thanks :)
Usually, for a many-to-many join you'd follow a pattern like;
public class Parent{
public int Id { get; set; }
public virtual ICollection<Join> Join { get; set; }
}
public class Join{
public int ParentId { get; set; }
public int ChildId { get; set; }
public virtual Parent Parent { get; set; }
public virtual Child Child { get; set; }
}
public class Child{
public int Id { get; set; }
public virtual ICollection<Join> Join { get; set; }
}
modelBuilder.Entity<Join>()
.HasOne(x => x.Parent)
.WithMany(x => x.Join)
.HasForeignKey(x => x.ParentId);
modelBuilder.Entity<Join>()
.HasOne(x => x.Child)
.WithMany(x => x.Join)
.HasForeignKey(x => x.ChildId);
But in your case you're trying to merge Parent and Child into the same type. You still need the same number of foreign keys and Navigation properties, but of course they'll all need to be unique.
public class Document{
public int Id { get; set; }
public virtual ICollection<DocumentOffset> Parents { get; set; }
public virtual ICollection<DocumentOffset> Children { get; set; }
}
public class DocumentOffset{
public int ParentId { get; set; }
public int ChildId { get; set; }
public virtual Document Parent { get; set; }
public virtual Document Child { get; set; }
}
modelBuilder.Entity<DocumentOffset>()
.HasOne(x => x.Parent)
.WithMany(x => x.Children)
.HasForeignKey(x => x.ParentId);
modelBuilder.Entity<DocumentOffset>()
.HasOne(x => x.Child)
.WithMany(x => x.Parents)
.HasForeignKey(x => x.ChildId);

One to Many relationship always bring me empty

I try to use Entity Framework with code first and fluent api to implement a one to many relationship
I have two classes
namespace Mantenimiento.Business.Entities
{
public class Personal : Entity
{
[Key]
public int Id { get; set; }
public int? Dni { get; set; }
public string Nombre { get; set; }
public string Apellido { get; set; }
public string Cuil { get; set; }
public string Legajo { get; set; }
[ForeignKey("Dni")]
public ICollection<ContactoEmergencia> Contacto { get; set; }
}
namespace Mantenimiento.Business.Entities
{
public class ContactoEmergencia : Entity
{
[Key]
public int Id { get; set; }
public int? Dni { get; set; }
public string ApellidoNombre { get; set; }
public string Vinculo { get; set; }
public string Domicilio { get; set; }
public string telefono { get; set; }
public string Comentario { get; set; }
public int CreateUserId { get; set; }
[ForeignKey("Dni")]
public virtual Personal Personal { get; set; }
}
}
This is my dbContext
#region personals
modelBuilder.Entity<Personal>().ToTable("InfoPersonal").HasKey(t => t.Id);
modelBuilder.Entity<Personal>().Property(c => c.Id).UseSqlServerIdentityColumn().IsRequired();
modelBuilder.Entity<Personal>().Property(c => c.CreatedDate).HasDefaultValue(DateTime.Now);
modelBuilder.Entity<Personal>().Property(c => c.LastModifiedDate).HasDefaultValue(DateTime.Now);
modelBuilder.Entity<Personal>().Property(c => c.Deleted).HasDefaultValue(false);
modelBuilder.Entity<Personal>().HasMany<ContactoEmergencia>(c => c.Contacto).WithOne(p => p.Personal).HasForeignKey(s => s.Dni);
#endregion
#region contactoEmergencias
modelBuilder.Entity<ContactoEmergencia>().ToTable("InfoEmergencia").HasKey(d => d.Dni);
modelBuilder.Entity<ContactoEmergencia>().Property(c => c.CreatedDate).HasDefaultValue(DateTime.Now);
modelBuilder.Entity<ContactoEmergencia>().Property(c => c.LastModifiedDate).HasDefaultValue(DateTime.Now);
modelBuilder.Entity<ContactoEmergencia>().Property(c => c.Deleted).HasDefaultValue(false);
#endregion
And my query is
return await _context.personals
.Include(c => c.Contacto)
.Where(p => p.Deleted == false)
.OrderBy(s => s.Apellido)
.ToListAsync(
);
But the properties is always empty.
i need to relate Personal.Di with Contacto.Dni, i had to change the key?
You should remove ForeignKey attribute from Personal entity. In one to many relationship only child entity could accept ForeignKey.

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();

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