I have two tables, InHandOrder & ExpRegistry. These table have a common column OrderNo.
When I insert data into the ExpRegistry table, it checks if InHandOrder table's OrderNo is equal to ExpRegistry table's OrderNo; if so, some of the column will automatically save into InHandOrder table that particular row in which OrderNo is matches.
I have tried something but data didn't save into the particular row but it's added a new row and save the data.
ExpRegistry controller class:
[HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status202Accepted)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public IActionResult Create(ExpRegistry obj)
{
if (ModelState.IsValid)
{
_unitOfWork.ExpRegistry.Add(obj);
_unitOfWork.Save();
IEnumerable<InHandOrder> objInHandOrderList = _unitOfWork.InHandOrder.GetAll().ToList();
var checkOrderNo = objInHandOrderList.FirstOrDefault(i => i.OrderNo == obj.OrderNo);
_unitOfWork.InHandOrder.Add(new InHandOrder()
{
InvoiceNo = obj.InvoiceNo,
ShipQty = obj.ShipQty,
InvoiceValue = obj.InvoiceValue
});
_unitOfWork.Save();
return CreatedAtAction("GetDetails", new { id = obj.Id }, obj);
}
_logger.LogError($"Something went wrong in the {nameof(Create)}");
return StatusCode(500, "Internal Server Error, Please Try Again Later!");
}
InHandOrder model class:
public class InHandOrder
{
[Key()]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
// Purchase Order
public int? ContractListId { get; set; }
[ForeignKey("ContractListId")]
[ValidateNever]
public ContractList? ContractList { get; set; }
public string? OrderNo { get; set; }
public int? StyleListId { get; set; }
[ForeignKey("StyleListId")]
[ValidateNever]
public StyleList? StyleList { get; set; }
public int? SeasonListId { get; set; }
[ForeignKey("SeasonListId")]
[ValidateNever]
public SeasonList? SeasonList { get; set; }
public DateTime? Shipment { get; set; }
public int? TotalQuantity { get; set; }
public decimal? UnitPrice { get; set; }
public decimal? PoValue { get; set; }
public int? CountryListId { get; set; }
[ForeignKey("CountryListId")]
[ValidateNever]
public CountryList? CountryList { get; set; }
// Export Register
public string? InvoiceNo { get; set; }
public int? ShipQty { get; set; }
public decimal? InvoiceValue { get; set; }
public decimal? ShortValue { get; set; }
public int? ShortQty { get; set; }
}
Here, InvoiceNo, ShipQty, InvoiceValue, shortValue, ShortQty fields will be saved when ExpRegistry is saved.
ExpRegistry model class:
public class ExpRegistry
{
[Key]
public int Id { get; set; }
public int? PoId { get; set; }
[DisplayName("Exp No")]
public string? ExpNo { get; set; }
[DisplayName("UNIT")]
public int? UnitListId { get; set; }
[ForeignKey("UnitListId")]
[ValidateNever]
public UnitList? UnitList { get; set; }
[Display(Name = "DATE")] //EXP ISSUE DATE
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime? ExpIssueDate { get; set; }
[DisplayName("ORDER NO")]
[ValidateNever]
public string? OrderNo { get; set; }
[DisplayName("INVOICE NO")]
[ValidateNever]
public string? InvoiceNo { get; set; }
[DisplayName("SHIPPED QTY")]
[ValidateNever]
public int? ShipQty { get; set; }
[DisplayName("VALUE")]
[DisplayFormat(DataFormatString = "{0:C}", ApplyFormatInEditMode = false)]
[ValidateNever]
public decimal? InvoiceValue { get; set; }
}
Please Help me to solve the issue. Thank you.
Related
I'm doing a project using ASP.NET Core MVC. I created my models and when I update the migration I got this error.
Introducing FOREIGN KEY constraint 'FK_Branch_Countries_CountriesId' on table 'Branch' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints
I went through the code and I hope there is nothing wrong with the foreign key assigned.
I hope the issue is Branch and Country both contain the CountryId for the foreign key. It should be connected to both tables connected with the Country table. But here it says can't create the table because of the cycle or multiple cascade paths.
So how to avoid this and do the migrations? Or the way I connected 3 tables are wrong?
Could you help me with this?
public class Countries
{
[Key]
public int Id { get; set; }
[Required]
public string Country_Name { get; set; }
public string Country_Code { get; set; }
public string Note { get; set; } = "N/A";
public bool Status { get; set; } = true;
public DateTime CreatedDate { get; set; } = DateTime.Now;
public int CreateBy { get; set; }
public DateTime ModifiedDate { get; set; } = DateTime.Now;
public int ModifiedBy { get; set; }
public virtual IList<Province> Province { get; set; }
public virtual IList<Branch> Branch { get; set; }
public Countries()
{
Province = new List<Province>();
Branch = new List<Branch>();
}
}
public class Province
{
[Key]
public int Id { get; set; }
[Required]
public string Province_Name { get; set; }
public string Province_Code { get; set; }
[Required]
[ForeignKey("Countries")]
public int Country_Id { get; set; }
public virtual Countries Countries { get; set; }
public string Note { get; set; } = "N/A";
public bool Status { get; set; } = true;
public DateTime CreatedDate { get; set; } = DateTime.Now;
public int CreateBy { get; set; }
public DateTime ModifiedDate { get; set; } = DateTime.Now;
public int ModifiedBy { get; set; }
public virtual IList<Cities> Cities { get; set; }
public virtual IList<Branch> Branch { get; set; }
public Province()
{
Cities = new List<Cities>();
Branch = new List<Branch>();
}
}
public class Cities
{
[Key]
public int Id { get; set; }
public string City_Name { get; set; }
[ForeignKey("Province")]
public int Province_Id { get; set; }
public virtual Province Province { get; set; }
public string Postal_Code { get; set; }
public string Istat_Code { get; set; }
public string Note { get; set; } = "N/A";
public bool Status { get; set; } = true;
public DateTime CreatedDate { get; set; } = DateTime.Now;
public int CreateBy { get; set; }
public DateTime ModifiedDate { get; set; } = DateTime.Now;
public int ModifiedBy { get; set; }
public virtual IList<Branch> Branch { get; set; }
public Cities()
{
Branch = new List<Branch>();
}
}
public class Branch
{
[Key]
public int Id { get; set; }
public string BranchName { get; set; }
public string Note { get; set; }
public int City_Id { get; set; }
public virtual Cities Cities { get; set; }
public int Province_Id { get; set; }
public virtual Province Province { get; set; }
public int Country_Id { get; set; }
public virtual Countries Countries { get; set; }
public string LocationEmailAddress { get; set; }
public string LocationContactNumber { get; set; }
public bool Status { get; set; } = true;
public DateTime CreatedDate { get; set; } = DateTime.Now;
public int CreateBy { get; set; }
public DateTime ModifiedDate { get; set; } = DateTime.Now;
public int ModifiedBy { get; set; }
public virtual IList<EmployeeLocations> EmployeeLocations { get; set; }
public Branch()
{
EmployeeLocations = new List<EmployeeLocations>();
}
}
It was caused by multiple cascade paths:
Branch-Country-Province-City
Branch-Province-City
Branch-City
You could check this case for more details:Foreign key constraint may cause cycles or multiple cascade paths?
Solution is very simple. You should remove ContryId from Branch, because ContryId is already referenced in Province.
I have 2 Tables in the SQL Server SUST_HC_DTLS [Primary Key Column Name = SUST_ID] and the second table is SUST_INC_TRCKR_DTLS [Foreign Key = SUST_HANDLER (it references SUST_ID column of first table. This Table also has a Primary Key column = INC_NBR)].Now when i create the Entity Data Model. It create 2 partial classes for both the Table. As show Below --
For Table = SUST_HC_DTLS (Primary Key Table)
public partial class SUST_HC_DTLS
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public SUST_HC_DTLS()
{
this.SUST_INC_TRCKR_DTLS = new HashSet<SUST_INC_TRCKR_DTLS>();
}
public int SUST_ID { get; set; }
public string HC_NAME { get; set; }
public string HC_EMAIL { get; set; }
public Nullable<System.TimeSpan> SHIFT_START { get; set; }
public Nullable<System.TimeSpan> SHIFT_END { get; set; }
public Nullable<System.DateTime> JOINED_ON { get; set; }
public Nullable<System.DateTime> UPDTD_AT { get; set; }
public string UPDTD_BY { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<SUST_INC_TRCKR_DTLS> SUST_INC_TRCKR_DTLS { get; set; }
}
For Secondary Table = SUST_INC_TRCKR_DTLS (Foreign Key Table)
public partial class SUST_INC_TRCKR_DTLS
{
public string INC_NBR { get; set; }
public string REASON_4_INC { get; set; }
public string RAISED_BY { get; set; }
public int SUST_HANDLER { get; set; }
public string COMMENTS { get; set; }
public string CURRENT_STTS { get; set; }
public Nullable<System.DateTime> CREATED_ON { get; set; }
public string DTLS_ENTRD_BY { get; set; }
public Nullable<System.DateTime> UPDTD_ON { get; set; }
public string DTLS_UPDTD_BY { get; set; }
public virtual SUST_HC_DTLS SUST_HC_DTLS { get; set; }
}
Now, I have separate Class Library for My Models for these respective Table and Below are the Classes in the Class Library --
For Primary Table --
public class HC_TBL
{
[Required]
public int SUST_ID { get; set; }
[Required]
public string HC_NAME { get; set; }
[EmailAddress]
public string HC_EMAIL { get; set; }
[Required]
[DataType(DataType.Time)]
public TimeSpan? SHIFT_START { get; set; }
[Required]
[DataType(DataType.Time)]
public TimeSpan? SHIFT_END { get; set; }
[Required]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? JOINED_ON { get; set; }
public DateTime? UPDTD_AT { get; set; }
public string UPDTD_BY { get; set; }
public INC_Trckr_TBL Trckr_TBL { get; set; }
}
For Foreign Key Table
public class INC_Trckr_TBL
{
public string INC_NBR { get; set; }
//[Required]
public string REASON_4_INC { get; set; }
//[Required]
public string RAISED_BY { get; set; }
public int SUST_HANDLER { get; set; }
public string COMMENTS { get; set; }
//[Required]
public string CURRENT_STTS { get; set; }
public DateTime? CREATED_ON { get; set; }
public string DTLS_ENTRD_BY { get; set; }
public DateTime? UPDTD_ON { get; set; }
public string DTLS_UPDTD_BY { get; set; }
}
Now when i do the Database Operations to get all records from the Database. Its not letting me call Foreign key properties /fields. It doesn't even provide them in the list.
However, when i do the LINQ Select from the options i get, i do get the property but then it gives me the error -- Cannot implicitly convert type System.Collections.Generic.IEnumerable to GDE.Model.INC_Trckr_TBL. An explicit conversion exists (Are you missing one?).
Now when i do the explicit conversion it says --
System.NotSupportedException
HResult=0x80131515
Message=Values of type 'collection[Edm.String(Nullable=True,DefaultValue=,MaxLength=20,Unicode=False,FixedLength=False)]' can not be converted to string.
I Honestly don't know what to do anymore. Below is my DBOperations Repository Code --
public List<SustHCModel> GetAllDetails()
{
using (var context = new GDE_SUSTEntities())
{
var result= context.SUST_HC_DTLS.Select(x => new SustHCModel()
{
SUST_ID = x.SUST_ID,
HC_NAME = x.HC_NAME,
HC_EMAIL = x.HC_EMAIL,
SHIFT_START = x.SHIFT_START,
SHIFT_END = x.SHIFT_END,
JOINED_ON = x.JOINED_ON,
IncTrckrModel = new INCTrckrModel()
{
INC_NBR = x.SUST_INC_TRCKR_DTLS.Select(y => y.INC_NBR).ToString(),
REASON_4_INC = x.SUST_INC_TRCKR_DTLS.Select(y => y.REASON_4_INC).ToString(),
RAISED_BY = x.SUST_INC_TRCKR_DTLS.Select(y => y.RAISED_BY).ToString(),
COMMENTS = x.SUST_INC_TRCKR_DTLS.Select(y => y.COMMENTS).ToString(),
CURRENT_STTS = x.SUST_INC_TRCKR_DTLS.Select(y => y.CURRENT_STTS).ToString()
}
}).ToList();
return result;
}
}
I am new to this. So, i am pretty sure that i have made some mistake somewhere. So, please guide me and my apologies in advance for whatever silly mistake i have made.
I have a class which has a many to many relationship with student. Please bare in mind this is a xarmain forms application talking to the client using NewtownSoft
public class Booking
{
public int Id { get; set; }
public int? DayOfWeek { get; set; }
public DateTime? BookingDate { get; set; }
public bool? IsAbsent { get; set; }
public DateTime? Time { get; set; }
public bool? HasCheckedIn { get; set; }
public ICollection<Student> Students { get; set; }
public bool? IsDeleted { get; set; }
public bool? IsActive { get; set; }
public string? CreatedBy { get; set; }
public string? LastModifiedBy { get; set; }
public DateTime? LastUpdatedDate { get; set; }
public DateTime? CreatedDate { get; set; }
}
Student Class
public class Student
{
public int Id { get; set; }
public int? Type { get; set; }
public string? FirstName { get; set; }
public string? Surname { get; set; }
public DateTime? DOB { get; set; }
public decimal? Weight { get; set; }
public decimal? Height { get; set; }
public int? Gender { get; set; }
public string? Photo { get; set; }
public int? Age { get; set; }
public ICollection<Booking> Bookings { get; set; }
public bool? IsDeleted { get; set; }
public ICollection<Notes>? Notes { get; set; }
public decimal? TB { get; set; }
public decimal? OP { get; set; }
public decimal? PU { get; set; }
public decimal? PB { get; set; }
public decimal? BP { get; set; }
public bool? IsActive { get; set; }
public string? CreatedBy { get; set; }
public string? LastModifiedBy { get; set; }
public DateTime? LastUpdatedDate { get; set; }
public DateTime? CreatedDate { get; set; }
}
I am adding that student to my api in the following way from the button click event.
private async void btnBookStudent_Clicked(object sender, EventArgs e)
{
//if we want the booking to include our student we must add it to our colleciton.
var test = Helpers.Dates.GetDateZeroTime(selectedBookingDate.Date).Add(timePicker.Time);
var student = await api.GetStudentById(StudentId);
var newBooking = new Booking
{
IsAbsent = false,
IsActive = true,
IsDeleted = false,
Time = Helpers.Dates.
GetDateZeroTime(selectedBookingDate.Date).
Add(timePicker.Time),
DayOfWeek = DayNumber
};
newBooking.Students = new List<Student>();
newBooking.Students.Add(student);
await api.AddToBooking(newBooking);
await DisplayAlert(Constants.AppName, "Booking Created For
Student", "OK");
}
However my client application is crashing out and not producing an error.
public async Task<HttpStatusCode> AddToBooking(Booking booking)
{
HttpStatusCode statusCode = new HttpStatusCode();
List<string> errors = new List<string>();
var serializerSettings = new JsonSerializerSettings {
ReferenceLoopHandling =
Newtonsoft.Json.ReferenceLoopHandling.Serialize};
string json =
JsonConvert.SerializeObject(booking,Formatting.Indented,
serializerSettings);
booking.CreatedBy = db.GetActiveUser();
var httpContent = new StringContent(json, Encoding.UTF8,
"application/json");
// AddAuthenicationHeader();
// Do the actual request and await the response
var httpResponse = await httpClient.PostAsync(Constants.BaseUrl + Constants.ApiSegmant + Constants.AddBooking, httpContent);
statusCode = httpResponse.StatusCode;
return statusCode;
}
As said before in my previous post its not giving me an error my Xamarin forms c# android application its just crashing at the JsonConvert line.
I have seen some articles suggesting turning off reference loop handling works but it doesn't in my case as I need to add the student at time of the booking.
How do I get more details error information on what is happening I tried adding.
On my booking class but it doesn't even get fired?. A try catch doesn't catch it either.
[OnError]
internal void OnError(StreamingContext context, ErrorContext errorContext)
{
var test = errorContext.Error;
}
I even tried [JsonIgnore] but i dont want that as I want the students to be with the bookings.
There is a self-referencing loop, as both models reference each other and if Json.NET was to serialise the object, it'd be stuck between Booking and Student.
Try ignoring the bookings from being serialised in every student using [JsonIgnore].
public class Student
{
public int Id { get; set; }
public int? Type { get; set; }
public string? FirstName { get; set; }
public string? Surname { get; set; }
public DateTime? DOB { get; set; }
public decimal? Weight { get; set; }
public decimal? Height { get; set; }
public int? Gender { get; set; }
public string? Photo { get; set; }
public int? Age { get; set; }
[JsonIgnore]
public ICollection<Booking> Bookings { get; set; }
public bool? IsDeleted { get; set; }
public ICollection<Notes>? Notes { get; set; }
public decimal? TB { get; set; }
public decimal? OP { get; set; }
public decimal? PU { get; set; }
public decimal? PB { get; set; }
public decimal? BP { get; set; }
public bool? IsActive { get; set; }
public string? CreatedBy { get; set; }
public string? LastModifiedBy { get; set; }
public DateTime? LastUpdatedDate { get; set; }
public DateTime? CreatedDate { get; set; }
}
When I send from Microsoft sql server to database then work fine.
But, when send post request from postman or angular, foreign data always is null.
I don't know where is problem.
This is class:
public class Korpa
{
public int Id { get; set; }
public int Id_korisnika { get; set; }
public Korisnik Korisnik { get; set; }
public int Id_Artikla { get; set; }
public Artikal Artikal { get; set; }
}
public class Artikal
{
public int Id { get; set; }
[Required(ErrorMessage = "Unesite naziv grupe artikla!")]
[StringLength(255)]
public string Grupa { get; set; }
[Required(ErrorMessage = "Unesite ime artikla!")]
[StringLength(255)]
public string Naziv_artikla { get; set; }
public decimal? Nabavna_cena { get; set; }
public decimal? Prodajna_cena { get; set; }
public short? kolicina { get; set; }
public string url_slike { get; set; }
public string Specifikacija { get; set; }
}
public class Korisnik
{
public int Id { get; set; }
[Required(ErrorMessage = "Unesite vase ime!")]
[StringLength(255)]
public string Ime { get; set; }
[Required(ErrorMessage = "Unesite vase prezime!")]
[StringLength(255)]
public string Prezime { get; set; }
[Required(ErrorMessage = "Unesite korisnicko ime!")]
[StringLength(255)]
public string Username { get; set; }
[Required(ErrorMessage = "Unesite sifru!")]
[StringLength(255)]
public string Sifra { get; set; }
[Required(ErrorMessage = "Unesite email")]
[StringLength(255)]
public string Email { get; set; }
[Required(ErrorMessage = "Unesite vasu adresu!")]
[StringLength(255)]
public string Adresa { get; set; }
[Required(ErrorMessage = "Unesite vas broj telefona!")]
[StringLength(255)]
public string Broj_telefona { get; set; }
public string jmbg { get; set; }
public int Nivo { get; set; }
}
This cotroller:
// GET: api/Korpas/5
[ResponseType(typeof(Korpa))]
public IHttpActionResult GetKorpa(int id)
{
var korpa = db.Korpa
.Include(c => c.Korisnik)
.Include(c => c.Artikal)
.SingleOrDefault(c => c.Id == id);
if (korpa == null)
{
return NotFound();
}
return Ok(korpa);
}
// POST: api/Korpas
[ResponseType(typeof(Korpa))]
public IHttpActionResult PostKorpa(Korpa korpa)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Korpa.Add(korpa);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = korpa.Id }, korpa);
}
Where is null, this send data from post request, where is not, then send sql query from ms sql server
SOLVED
public class Korpa
{
public int Id { get; set; }
public int Id_korisnika { get; set; }
[ForeignKey("Id_korisnika")]
public Korisnik Korisnik { get; set; }
public int Id_Artikla { get; set; }
[ForeignKey("Id_Artikla")]
public Artikal Artikal { get; set; }
}
Just add [ForeignKey("name of foreign key")]
Your POST method receives a Korpa model, but the entity does not have the Artikal_Id property, you must add the property to the Korpa model so that the web api can perform the serialization.
public class Korpa
{
public int Id { get; set; }
public int Id_korisnika { get; set; }
public Korisnik Korisnik { get; set; }
public int Id_Artikla { get; set; }
public Artikal Artikal { get; set; }
public int Artikal_Id {get; set;} // Add this property
}
I am using EF6.1.3. I have 3 poco's pickbatch, order, orderline.
public class PickBatch
{
public int Id { get; set; }
public string Barcode { get; set; }
public byte Status { get; set; }
public string Picker { get; set; }
public DateTime DateCreated { get; set; }
public DateTime? DateModified { get; set; }
public List<Order> Orders { get; set; }
}
public class Boxes
{
public Order()
{
OrderLines = new List<OrderLines>();
}
public int Id { get; set; }
public int? PickBatchId { get; set; }
public string OrderType { get; set; }
public string OrderNumber { get; set; }
public string CustomerNumber { get; set; }
public byte Status { get; set; }
public DateTime DateCreated { get; set; }
public DateTime? DateModified { get; set; }
public List<OrderLine> OrderLines { get; set; }
}
public class OrderLines
{
public int Id { get; set; }
public string Article { get; set; }
public string ArticleDescription { get; set; }
public int QtyOrdered { get; set; }
public int QtyDelivered { get; set; }
public int OrderId { get; set; }
public byte Status { get; set; }
public string Picker { get; set; }
public string PickLocation { get; set; }
public string Sorting { get; set; }
public DateTime DateCreated { get; set; }
public DateTime? DateModified { get; set; }
}
Not all the properties match the column names in the tables. So on model creating i am fixing this.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<PickBatch>().ToTable("PickBatch");
modelBuilder.Entity<PickBatch>().HasKey(b => b.Id);
modelBuilder.Entity<PickBatch>().Property(b => b.Id).HasColumnName("PickBatchId");
modelBuilder.Entity<Order>().HasKey(b => b.Id);
modelBuilder.Entity<Order>().Property(b => b.Id).HasColumnName("OrderId");
modelBuilder.Entity<OrderLine>().HasKey(b => b.Id);
modelBuilder.Entity<OrderLine>().Property(o => .Id).HasColumnName("OrderLineId");
}
When retrieve the orderlines I get an execption: Invalid column name 'PickBatch_Id'. I don't understand why does EF want to add this property?