How insert, update and delete data with a view - c#

I want to get, update, delete and insert data in a view. So far I can get and update data from the view. I use Entity Framework Core 2.1 version.
This is the view model:
public partial class vwVacation: IEntity
{
public int EmployeeId { get; private set; }
public string EmployeeName { get; private set; }
public string EmployeeSurName { get; private set; }
public string EmployeeOccupation { get; private set; }
public string EmployeePhone { get; private set; }
public string EmployeeEmail { get; private set; }
public int HeadQuartersId { get; private set; }
public string HeadQuartersName { get; private set; }
public string HeadQuartersCode { get; private set; }
public int VacationId { get; set; }
public int VacationTypeId { get; set; }
public string VacationType{ get; private set; }
[Column("HistoryId")]
public int Id { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public int VacationDaysTake{ get; set; }
public bool IsApproved { get; set; }
}
This is the code that I write in the entity context:
public virtual DbSet<vwVacation> vwVacation{ get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<vwVacation>(entity =>
{
entity.HasKey(e => e.Id);
entity.Property(e => e.EndDate).HasColumnType("datetime");
entity.Property(e => e.StartDate).HasColumnType("datetime");
entity.Property(e => e.IsApproved)
.HasColumnType("bit")
.HasDefaultValueSql("('0')");
entity.ToTable("vwVacation");
entity.Property(e => e.EmployeeId)
.Metadata.AfterSaveBehavior = PropertySaveBehavior.Throw;
entity.Property(e => e.EmployeeName)
.Metadata.AfterSaveBehavior = PropertySaveBehavior.Throw;
entity.Property(e => e.EmployeeSurName)
.Metadata.AfterSaveBehavior = PropertySaveBehavior.Throw;
entity.Property(e => e.EmployeeOccupation)
.Metadata.AfterSaveBehavior = PropertySaveBehavior.Throw;
entity.Property(e => e.EmployeePhone)
.Metadata.AfterSaveBehavior = PropertySaveBehavior.Throw;
entity.Property(e => e.EmployeeEmail)
.Metadata.AfterSaveBehavior = PropertySaveBehavior.Throw;
entity.Property(e => e.HeadQuartersId)
.Metadata.AfterSaveBehavior = PropertySaveBehavior.Throw;
entity.Property(e => e.HeadQuartersName)
.Metadata.AfterSaveBehavior = PropertySaveBehavior.Throw;
entity.Property(e => e.HeadQuartersCode)
.Metadata.AfterSaveBehavior = PropertySaveBehavior.Throw;
entity.Property(e => e.VacationType)
.Metadata.AfterSaveBehavior = PropertySaveBehavior.Throw;
});
}
What I need to do to insert data in my view and entity framework know which column are for insert and which column are ReadOnly ?

Related

Entity Framework getting Branches table throws an exception from the type Microsoft.Data.SqlClient.SqlException I don't know why

I'm using entity framework in ASP.NET Core Web API project
I have built the model using the scaffold command from the package manager console and everything is working properly, I can edit the tables, I can insert data, I can update, get lists of data using many different criteria.
any ways my problem is when I try to get all the data from a table named 'Branches'
I get an error of type Microsoft.Data.SqlClient.SqlException with a message says "Invalid column name 'UserIndx'."
this is my code that tries to get the data
/// <summary>
/// Function that returns a list with all the branch table data.
/// </summary>
public List<Branch> getBranches()
{
List<Branch> list = new List<Branch>();
try
{
list = db.Branches.ToList();
return list;
}
catch(Exception ex)
{
er.writeToErrorLog("BLDataEntry", "Branches", "getBranches", ex);
return list;
}
}
This is my branch class that was auto generated by the scaffold command
public partial class Branch
{
public int Indx { get; set; }
public string Branch1 { get; set; } = null!;
public string? IataNo { get; set; }
public int? VatDealer { get; set; }
public string? Tel { get; set; }
public string? Tel2 { get; set; }
public string? Fax { get; set; }
public string? Fax2 { get; set; }
public string? Address { get; set; }
public int? SagentId { get; set; }
public int? OutAccGroup { get; set; }
public int? IntAccGroup { get; set; }
public int? IncAccGroup { get; set; }
public int? IspAccGroup { get; set; }
public byte[]? RptLogo { get; set; }
public byte[]? AppLogo { get; set; }
public int? Company { get; set; }
public DateTime OpenDate { get; set; }
public bool SellOnly { get; set; }
public bool? IsOblClientDetails { get; set; }
public DateTime? CloseDate { get; set; }
public string? LocalName { get; set; }
public string? LocalAddress { get; set; }
public string? Longitude { get; set; }
public string? Latitude { get; set; }
public string? WorkingDaysHours { get; set; }
public string? Iban { get; set; }
public string? KvKnr { get; set; }
public string? Btwnr { get; set; }
public string? Biccode { get; set; }
public byte[]? AddLogos { get; set; }
public string? Email { get; set; }
public string? WebSite { get; set; }
public virtual ICollection<AccBank> AccBanks { get; } = new List<AccBank>();
public virtual ICollection<Agent> Agents { get; } = new List<Agent>();
public virtual ICollection<Department> Departments { get; } = new List<Department>();
public virtual ICollection<SpecialProductDistribution> SpecialProductDistributions { get; } = new List<SpecialProductDistribution>();
}
This is the code from the dbContext.cs that also was auto generated by the scaffold command by entity framework
modelBuilder.Entity<Branch>(entity =>
{
entity.HasKey(e => e.Indx);
entity.Property(e => e.AddLogos).HasColumnType("image");
entity.Property(e => e.Address).HasMaxLength(50);
entity.Property(e => e.AppLogo).HasColumnType("image");
entity.Property(e => e.Biccode)
.HasMaxLength(10)
.HasColumnName("BICcode");
entity.Property(e => e.Branch1)
.HasMaxLength(50)
.HasColumnName("Branch");
entity.Property(e => e.Btwnr)
.HasMaxLength(15)
.HasColumnName("BTWnr");
entity.Property(e => e.CloseDate).HasColumnType("datetime");
entity.Property(e => e.Email).HasMaxLength(100);
entity.Property(e => e.Fax).HasMaxLength(15);
entity.Property(e => e.Fax2).HasMaxLength(15);
entity.Property(e => e.IataNo).HasMaxLength(12);
entity.Property(e => e.Iban)
.HasMaxLength(50)
.HasColumnName("IBAN");
entity.Property(e => e.IsOblClientDetails)
.IsRequired()
.HasDefaultValueSql("((1))");
entity.Property(e => e.KvKnr)
.HasMaxLength(15)
.HasColumnName("KvKNr");
entity.Property(e => e.Latitude)
.HasMaxLength(15)
.HasColumnName("latitude");
entity.Property(e => e.LocalAddress).HasMaxLength(100);
entity.Property(e => e.LocalName).HasMaxLength(100);
entity.Property(e => e.Longitude)
.HasMaxLength(15)
.HasColumnName("longitude");
entity.Property(e => e.OpenDate)
.HasDefaultValueSql("(getdate())")
.HasColumnType("datetime");
entity.Property(e => e.RptLogo).HasColumnType("image");
entity.Property(e => e.SagentId).HasColumnName("SAgentID");
entity.Property(e => e.Tel).HasMaxLength(15);
entity.Property(e => e.Tel2).HasMaxLength(15);
entity.Property(e => e.WebSite).HasMaxLength(100);
entity.Property(e => e.WorkingDaysHours).HasMaxLength(255);
});
I have searched the whole project for a column with the name UserIndx and it doesn't exist in my whole solution I have tried to pull a specific column from that table and it worked right as it should
the problem is basically when I wanna grab all the table into a list.
I have tried getting back data when I asked for specific columns.

How to map a unidirectional many-to-one relationship?

I have an Item entity:
public class Item
{
public long Id { get; set; }
public string Name { get; set; }
public string Skuid { get; set; }
public double Price { get; set; }
public double Amount { get; set; }
}
And an Order entity:
public class Order
{
public long Id { get; set; }
public DateTime Date { get; set; }
public StatusEnum Status { get; set; }
public long SellerId { get; set; }
public Seller Seller { get; set; }
public double Total { get; set; }
public IList<Item> Items { get; set; }
}
My objective is to save the Order containing the items in the Database, but when the request is made, only the reference of my entity "Seller" is saved, but not the references of the items.
I did the following mapping on the "Order" entity:
public class OrderMap : IEntityTypeConfiguration<Order>
{
public void Configure(EntityTypeBuilder<Order> builder)
{
builder.ToTable("Orders");
builder.HasKey(x => x.Id);
builder.Property(x => x.Id)
.ValueGeneratedOnAdd()
.UseIdentityColumn();
builder.Property(x => x.Date)
.IsRequired()
.HasColumnName("DateSale")
.HasColumnType("DATETIME")
.HasDefaultValueSql("GETDATE()");
builder.Property(x => x.Total)
.IsRequired()
.HasColumnName("Total")
.HasColumnType("DECIMAL");
builder.Property(x => x.Status)
.IsRequired()
.HasConversion(
v => v.ToString(),
v => (StatusEnum)Enum.Parse(typeof(StatusEnum), v))
.HasColumnName("Status")
.HasColumnType("NVARCHAR") //verificar se nao vai dar conflito
.HasMaxLength(120);
builder
.HasOne(x => x.Seller)
.WithOne()
.HasConstraintName("FK_Seller_Order")
.OnDelete(DeleteBehavior.Cascade);
builder
.HasMany(x => x.Items)
.WithOne()
.HasConstraintName("FK_Item_Order")
.IsRequired()
.OnDelete(DeleteBehavior.Cascade); //
}
}
What is the correct mapping to do?
Please first add these properties OrderId and Order to your Item entity class. This way you are instructions the framework to create an OrderId foreign key
column in the database.
public class Item
{
public long Id { get; set; }
public string Name { get; set; }
public string Skuid { get; set; }
public double Price { get; set; }
public double Amount { get; set; }
public long OrderId { get; set; }
public Order Order {get; set; }
}
And perhaps this part
builder.HasMany(x => x.Items).WithOne()
should be like this
builder.HasMany(x => x.Items).WithOne(x => x.Order)

How to Correctly Handle Reference Loop .NET Entity Framework API

I have two tables and related code files, Request and RequestLine. One Request can have many RequestLines. I used a database first approach and the models were automatically created using scaffolding. I am using Entity Framework and DTOs etc
I have run into an issue where i'm getting a Reference Loop error in my API when running the POST method.
The issue occurs because the scaffold put a Request property in the RequestLine object
public virtual Request Request { get; set; } = null!;
With my GET method, in the controller I was able to point it to its related DTO, where I removed the Request field which would have caused the reference loop but i'm not sure how I would achieve the same with the POST method. I created a RequestCreateDTO and RequestLineCreateDTO without the reference field loop but I can't figure out how to use this in my POST.
I have found two ways of avoiding this issue
The first is to remove the Request property from RequestLine model, then remove the relationship from RequesLine context
Alternatively, I can add this to my Program.cs to ignore the Reference Loop
builder.Services.AddControllers().AddJsonOptions(x =>
x.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles);
Although both work, neither seems like to correct way to handle this. So I was wondering how I go about handling it properly? I want to POST a Request, which contains a RequestLine - But I want them to use my RequestCreateDTO and RequestLineCreateDTO.
The related code is below.
The data context for Request and RequestLines is:
modelBuilder.Entity<Request>(entity =>
{
entity.ToTable("Request", "rmr");
entity.Property(e => e.CreatedOn).HasColumnType("datetime");
entity.Property(e => e.RaisedBy).HasMaxLength(256);
entity.Property(e => e.WorklistName).HasMaxLength(32);
//entity.HasOne(d => d.WorklistNameNavigation)
// .WithMany(p => p.Requests)
// .HasForeignKey(d => d.WorklistName)
// .HasConstraintName("FK_RMR_REQUEST_WORKLIST");
});
modelBuilder.Entity<RequestLine>(entity =>
{
entity.HasKey(e => new { e.RequestId, e.LineNumber })
.HasName("PK_RMR_REQUESTLINE");
entity.ToTable("RequestLine", "rmr");
entity.Property(e => e.Batch).HasMaxLength(32);
entity.Property(e => e.CancelBy).HasMaxLength(256);
entity.Property(e => e.CancelDate).HasColumnType("datetime");
entity.Property(e => e.CostCentre).HasMaxLength(32);
entity.Property(e => e.Destination).HasMaxLength(32);
entity.Property(e => e.FirstDeliveryDate).HasColumnType("datetime");
entity.Property(e => e.ProcessOrder).HasMaxLength(32);
entity.Property(e => e.Sku)
.HasMaxLength(32)
.HasColumnName("SKU");
entity.Property(e => e.SubmittedDate).HasColumnType("datetime");
//entity.HasOne(d => d.DestinationNavigation)
// .WithMany(p => p.RequestLines)
// .HasForeignKey(d => d.Destination)
// .OnDelete(DeleteBehavior.ClientSetNull)
// .HasConstraintName("FK_RMR_REQUESTLINE_DESTINATION");
entity.HasOne(d => d.Request)
.WithMany(p => p.RequestLines)
.HasForeignKey(d => d.RequestId)
.HasConstraintName("FK_RMR_REQUESTLINE_REQUEST");
});
The related data models are as follows:
Request
public partial class Request
{
public Request()
{
RequestLines = new HashSet<RequestLine>();
}
public long Id { get; set; }
public string RaisedBy { get; set; } = null!;
public DateTime CreatedOn { get; set; }
public string? WorklistName { get; set; }
//public virtual Worklist? WorklistNameNavigation { get; set; }
public virtual ICollection<RequestLine> RequestLines { get; set; }
}
RequestLine
public partial class RequestLine
{
public long RequestId { get; set; }
public int LineNumber { get; set; }
public string Sku { get; set; } = null!;
public string Batch { get; set; } = null!;
public int Quantity { get; set; }
public string? CostCentre { get; set; }
public string? ProcessOrder { get; set; }
public string Destination { get; set; } = null!;
public DateTime FirstDeliveryDate { get; set; }
public DateTime? SubmittedDate { get; set; }
public DateTime? CancelDate { get; set; }
public string? CancelBy { get; set; }
}
}
and the DTOs for the POST method is:
Request
public class RequestCreateDTO
{
public RequestCreateDTO()
{
RequestLines = new HashSet<RequestLineCreateDTO>();
}
[Required]
[StringLength(256)]
public string RaisedBy { get; set; } = null!;
[Required]
public DateTime CreatedOn { get; set; }
[Required]
[StringLength(32)]
public string? WorklistName { get; set; }
//public virtual Worklist? WorklistNameNavigation { get; set; }
public virtual ICollection<RequestLineCreateDTO> RequestLines { get; set; }
}
RequestLine
public class RequestLineCreateDTO
{
[Required]
public int LineNumber { get; set; }
[Required]
[StringLength(32)]
public string Sku { get; set; } = null!;
[Required]
[StringLength(32)]
public string Batch { get; set; } = null!;
public int Quantity { get; set; }
[StringLength(32)]
public string? CostCentre { get; set; }
[StringLength(32)]
public string? ProcessOrder { get; set; }
[Required]
[StringLength(32)]
public string Destination { get; set; } = null!;
public DateTime FirstDeliveryDate { get; set; }
public DateTime? SubmittedDate { get; set; }
public DateTime? CancelDate { get; set; }
[Required]
[StringLength(256)]
public string? CancelBy { get; set; }
}
The point at which i'm having an issue is my POST method and the controller looks like this
[HttpPost]
public async Task<ActionResult<RequestCreateDTO>> PostRequest(RequestCreateDTO requestDto)
{
var request = mapper.Map<Request>(requestDto);
//var requestLine = mapper.Map<RequestLine>(requestLineDto);
if (_context.Requests == null)
{
return Problem("Entity set 'RawcliffeDatastoreContext.Requests' is null.");
}
await _context.Requests.AddAsync(request);
//await _context.RequestLines.AddAsync(requestLine);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetRequest), new { id = request.Id }, request);
}

Entity Framework Core with Multiple Foreign Key On Same Column

I have 3 tables with relationship to the same TransactionLog.DocumentId column.
I differentiate the Foreign Key with DocumentTypeId:
1 - Invoice,
2 - DebitNote,
3 - CreditNote
I scaffold the entities:
public partial class TransactionLog
{
public int TransactionLogId { get; set; }
public int? DocumentId { get; set; }
public int? DocumentTypeId { get; set; }
public decimal? Amount { get; set; }
public CreditNote CreditNote { get; set; }
public Invoice Invoice { get; set; }
public DebitNote DebitNote { get; set; }
}
public partial class Invoice
{
public Invoice()
{
TransactionLog = new HashSet<TransactionLog>();
}
public int InvoiceId { get; set; }
public string InvoiceNumber { get; set; }
public decimal Amount { get; set; }
public ICollection<TransactionLog> TransactionLog { get; set; }
}
public partial class DebitNote
{
public DebitNote()
{
TransactionLog = new HashSet<TransactionLog>();
}
public int DebitNoteId { get; set; }
public string DebitNoteNumber { get; set; }
public decimal Amount { get; set; }
public ICollection<TransactionLog> TransactionLog { get; set; }
}
public partial class CreditNote
{
public CreditNote()
{
TransactionLog = new HashSet<TransactionLog>();
}
public int CreditNoteId { get; set; }
public string CreditNoteNumber { get; set; }
public decimal Amount { get; set; }
public ICollection<TransactionLog> TransactionLog { get; set; }
}
I want to insert 1 record to each of the table Invoice, DebitNote and CreditNote, and 3 records for each transaction to TransactionLog.
And this is my code:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<CreditNote>(entity =>
{
entity.Property(e => e.Amount).HasColumnType("decimal(18, 4)");
entity.Property(e => e.CreditNoteNumber)
.HasMaxLength(50)
.IsUnicode(false);
});
modelBuilder.Entity<DebitNote>(entity =>
{
entity.Property(e => e.Amount).HasColumnType("decimal(18, 4)");
entity.Property(e => e.DebitNoteNumber)
.HasMaxLength(50)
.IsUnicode(false);
});
modelBuilder.Entity<Invoice>(entity =>
{
entity.Property(e => e.Amount).HasColumnType("decimal(18, 4)");
entity.Property(e => e.InvoiceNumber)
.HasMaxLength(50)
.IsUnicode(false);
});
modelBuilder.Entity<TransactionLog>(entity =>
{
entity.Property(e => e.Amount).HasColumnType("decimal(18, 4)");
entity.HasOne(d => d.CreditNote)
.WithMany(p => p.TransactionLog)
.HasForeignKey(d => d.DocumentId)
.HasConstraintName("FK_TransactionLog_CreditNote");
entity.HasOne(d => d.DebitNote)
.WithMany(p => p.TransactionLog)
.HasForeignKey(d => d.DocumentId)
.HasConstraintName("FK_TransactionLog_DebitNote");
entity.HasOne(d => d.Invoice)
.WithMany(p => p.TransactionLog)
.HasForeignKey(d => d.DocumentId)
.HasConstraintName("FK_TransactionLog_Invoice");
});
}
However, the DocumentId doesn't save the correct InvoiceId, CreditNoteId, DebitNoteId. I check with SQL Profiler, it will always get the first scope_identity() of the 3 inserts, which in my case is CreditNoteid.
Any idea how to get the correct Id from Invoice, CreditNote and DebitNote ?
Or shouldn't I use relationship in this case.
If not, what is the best practice of logging the transaction into the log?
Add the following configurations in your DbContext and then add a migration and update the database accordingly.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Invoice>().HasMany(i => i.TransactionLog).WithOne(tl => tl.Invoice).HasForeignKey(tl => tl.DocumentId);
modelBuilder.Entity<DebitNote>().HasMany(dn => dn.TransactionLog).WithOne(tl => tl.DebitNote).HasForeignKey(tl => tl.DocumentId);
modelBuilder.Entity<CreditNote>().HasMany(cn => cn.TransactionLog).WithOne(tl => tl.CreditNote).HasForeignKey(tl => tl.DocumentId);
}
I think maybe the Foreign Key's direction is wrong.
As your table definition, the TransactionLog.DocumentId's value must be exist in the three tables (Invoice CreditNote DebitNote) at the same time. So, if only insert two of them, there will maybe have a Exception.
I think you really want table definition is like this.
I delete TransactionLog.DocumentId column and add FKs from the PK of the three tables to TransactionLog.TransactionLogId.
the entities:
public partial class TransactionLog
{
public int TransactionLogId { get; set; }
public Nullable<int> DocumentTypeId { get; set; }
public Nullable<decimal> Amount { get; set; }
public virtual CreditNote CreditNote { get; set; }
public virtual DebitNote DebitNote { get; set; }
public virtual Invoice Invoice { get; set; }
}
public partial class Invoice
{
public int InvoiceId { get; set; }
public string InvoiceNumber { get; set; }
public decimal Amount { get; set; }
public virtual TransactionLog TransactionLog { get; set; }
}
public partial class CreditNote
{
public int CreditNoteId { get; set; }
public string CreditNoteNumber { get; set; }
public decimal Amount { get; set; }
public virtual TransactionLog TransactionLog { get; set; }
}
public partial class DebitNote
{
public int DebitNoteId { get; set; }
public string DebitNoteNumber { get; set; }
public decimal Amount { get; set; }
public virtual TransactionLog TransactionLog { get; set; }
}
code:
Invoice invoice = new Invoice() { InvoiceNumber = "Inv0100", Amount = 66m };
TransactionLog invoiceLog = new TransactionLog() { Amount = invoice.Amount, DocumentTypeId = 1 };
invoice.TransactionLog = invoiceLog;
_context.Invoices.Add(invoice);
CreditNote creditNote = new CreditNote() { CreditNoteNumber = "DN003", Amount = 99.99m };
TransactionLog creditNoteLog = new TransactionLog() { Amount = creditNote.Amount, DocumentTypeId = 2 };
creditNote.TransactionLog = creditNoteLog;
_context.CreditNotes.Add(creditNote);
DebitNote debitNote = new DebitNote() { DebitNoteNumber = "CN009", Amount = 77.77m };
TransactionLog debitNoteLog = new TransactionLog() { Amount = debitNote.Amount, DocumentTypeId = 3 };
debitNote.TransactionLog = debitNoteLog;
_context.DebitNotes.Add(debitNote);
I guess you have a wrong relationship there. like one transaction can have multiple invoices but an invoice will have only one transaction record. I might be wrong because sometimes it feels like one-to-one but anyways I gave it a try and here is what you want.
the entities:
public class TestMVCEntities : DbContext
{
public TestMVCEntities()
: base("name=TestMVCEntities")
{
}
public DbSet<Invoice> Invoices { get; set; }
public DbSet<DebitNote> DebitNotes { get; set; }
public DbSet<CreditNote> CreditNotes { get; set; }
public DbSet<TransactionLog> TransactionLogs { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<TransactionLog>()
.HasRequired(p => p.Invoice)
.WithMany(p => p.InvoiceLog)
.HasForeignKey(p => p.DocumentId);
modelBuilder.Entity<TransactionLog>()
.HasRequired(p => p.DebitNote)
.WithMany(p => p.DebitLog)
.HasForeignKey(p => p.DocumentId);
modelBuilder.Entity<TransactionLog>()
.HasRequired(p => p.CreditNote)
.WithMany(p => p.CreditLog)
.HasForeignKey(p => p.DocumentId);
}
}
public partial class TransactionLog
{
public int TransactionLogId { get; set; }
public int? DocumentId { get; set; }
public int? DocumentTypeId { get; set; }
public decimal? Amount { get; set; }
public CreditNote CreditNote { get; set; }
public Invoice Invoice { get; set; }
public DebitNote DebitNote { get; set; }
}
public partial class Invoice
{
public int InvoiceId { get; set; }
public string InvoiceNumber { get; set; }
public decimal Amount { get; set; }
public ICollection<TransactionLog> InvoiceLog { get; set; }
}
public partial class DebitNote
{
public int DebitNoteId { get; set; }
public string DebitNoteNumber { get; set; }
public decimal Amount { get; set; }
public ICollection<TransactionLog> DebitLog { get; set; }
}
public partial class CreditNote
{
public int CreditNoteId { get; set; }
public string CreditNoteNumber { get; set; }
public decimal Amount { get; set; }
public ICollection<TransactionLog> CreditLog { get; set; }
}
and to insert data:
var invoice = new Invoice()
{
InvoiceNumber = "Inv099",
Amount = 66m,
InvoiceLog = new Collection<TransactionLog>()
{
new TransactionLog(){DocumentTypeId = 1, Amount = 66m}
}
};
var creditNote = new CreditNote()
{
CreditNoteNumber = "DN002",
Amount = 99.99m,
CreditLog = new Collection<TransactionLog>()
{
new TransactionLog(){DocumentTypeId = 3, Amount = 99.99m}
}
};
var debitNote = new DebitNote()
{
DebitNoteNumber = "CN008",
Amount = 77.77m,
DebitLog = new Collection<TransactionLog>()
{
new TransactionLog(){DocumentTypeId = 2, Amount = 77.77m}
}
};
using (var context = new TestMVCEntities())
{
context.Invoices.Add(invoice);
context.CreditNotes.Add(creditNote);
context.DebitNotes.Add(debitNote);
context.SaveChanges();
}
and the table will look like this:

Entity Framework core: Invalid column name

I have this database model:
public partial class Image
{
public Image()
{
EntityImages = new List<EntityImage>();
}
public int Id { get; set; }
public string Content { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedDate { get; set; }
public string ModifiedBy { get; set; }
public DateTime? ModifiedDate { get; set; }
public bool IsDeleted { get; set; }
public ICollection<EntityImage> EntityImages { get; set; }
}
public partial class EntityImage
{
public int Id { get; set; }
public int ImageId { get; set; }
public int EntityId { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedDate { get; set; }
public string ModifiedBy { get; set; }
public DateTime? ModifiedDate { get; set; }
public bool IsDeleted { get; set; }
[ForeignKey("EntityId")]
public Entity Entity { get; set; }
[ForeignKey("ImageId")]
public Image Image { get; set; }
}
I used database first, and when I am trying to make an insert into Images tables, I got the "Invalid column name: EntityId" error.
This is the context code:
modelBuilder.Entity<EntityImage>(entity =>
{
entity.Property(e => e.CreatedBy).HasMaxLength(50);
entity.Property(e => e.CreatedDate).HasColumnType("datetime");
entity.Property(e => e.ModifiedBy).HasMaxLength(50);
entity.Property(e => e.ModifiedDate).HasColumnType("datetime");
entity.HasOne(d => d.Entity)
.WithMany(p => p.EntityImages)
.HasForeignKey(d => d.EntityId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_CategorySubcategory_Entities");
entity.HasOne(d => d.Image)
.WithMany(p => p.EntityImages)
.HasForeignKey(d => d.ImageId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_CategorySubcategory_Images");
});
modelBuilder.Entity<Image>(entity =>
{
entity.Property(e => e.Content)
.IsRequired()
.HasMaxLength(50);
entity.Property(e => e.CreatedBy).HasMaxLength(50);
entity.Property(e => e.CreatedDate).HasColumnType("datetime");
entity.Property(e => e.ModifiedBy).HasMaxLength(50);
entity.Property(e => e.ModifiedDate).HasColumnType("datetime");
});
I do not know where the error is.
I do not know why Entity Framework try to insert a image record with a EntityId column since it columns does not exists in that table.
I have the same model for categories, subcategories and categoriesSubcategories tables and the code work without any problems.

Categories

Resources