I am stuck with an error i can't figure out. I have a complex model with several circular references. I have tried everything i know to handle them but i am still getting a internal server error (code 500) when i attempt saving.
Below are the models and controllers:
public partial class Event
{
public Event()
{
Recurrences = new HashSet<Recurrence>();
}
public int Id { get; set; }
[Required]
[StringLength(150)]
public string Title { get; set; }
public DateTime CreateDate { get; set; }
public DateTime UpdateDate { get; set; }
[StringLength(128)]
public string CreatedBy { get; set; }
[StringLength(128)]
public string UpdatedBy { get; set; }
public ICollection<Recurrence> Recurrences { get; set; }
}
public partial class Recurrence
{
public Recurrence()
{
AspNetUsers = new HashSet<AspNetUser>();
}
public int Id { get; set; }
public int EventId { get; set; }
[Column(TypeName = "date")]
public DateTime StartDate { get; set; }
[Column(TypeName = "date")]
public DateTime? EndDate { get; set; }
public bool? AllDay { get; set; }
public TimeSpan? StartTime { get; set; }
public TimeSpan? EndTime { get; set; }
[StringLength(500)]
public string Venue { get; set; }
public double? Longitude { get; set; }
public double? Latitude { get; set; }
public int? RecurrenceInterval { get; set; }
public bool? ExcludeWeekends { get; set; }
public DateTime CreateDate { get; set; }
public DateTime UpdateDate { get; set; }
[StringLength(128)]
public string CreatedBy { get; set; }
[StringLength(128)]
public string UpdatedBy { get; set; }
public Event Event { get; set; }
public RecurrenceType RecurrenceType { get; set; }
public ICollection<AspNetUser> AspNetUsers { get; set; }
}
public partial class AspNetUser
{
public AspNetUser()
{
Recurrences = new HashSet<Recurrence>();
}
public string Id { get; set; }
[StringLength(256)]
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; }
[Required]
[StringLength(256)]
public string UserName { get; set; }
public ICollection<Recurrence> Recurrences { get; set; }
}
public class EventDTO
{
public int Id { get; set; }
[Required]
[StringLength(150)]
public string Title { get; set; }
public int EventTypeId { get; set; }
[Column(TypeName = "date")]
public DateTime StartDate { get; set; }
[Column(TypeName = "date")]
public DateTime EndDate { get; set; }
public bool? AllDay { get; set; }
public TimeSpan? StartTime { get; set; }
public TimeSpan? EndTime { get; set; }
[StringLength(500)]
public string Venue { get; set; }
public double? Longitude { get; set; }
public double? Latitude { get; set; }
public int RecurrenceTypeId { get; set; }
public int? RecurrenceInterval { get; set; }
public bool? ExcludeWeekends { get; set; }
public DateTime CreateDate { get; set; }
public DateTime UpdateDate { get; set; }
[StringLength(128)]
public string CreatedBy { get; set; }
[StringLength(128)]
public string UpdatedBy { get; set; }
public List<string> UserId { get; set; }
}
public async Task<IHttpActionResult> PostEvent(EventDTO #event)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Event newEvent = new Event();
newEvent.Title = #event.Title;
newEvent.EventTypeId = #event.EventTypeId;
newEvent.CreateDate = #event.CreateDate;
newEvent.UpdateDate = #event.UpdateDate;
newEvent.CreatedBy = #event.CreatedBy;
newEvent.UpdatedBy = #event.CreatedBy;
if (newEvent == null) {
throw new HttpResponseException(
Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "Error creating Event"));
}
Recurrence recurrence = new Recurrence();
recurrence.StartDate = #event.StartDate;
recurrence.EndDate = #event.EndDate;
recurrence.AllDay = #event.AllDay;
recurrence.StartTime = #event.StartTime;
recurrence.EndTime = #event.EndTime;
recurrence.Venue = #event.Venue;
recurrence.Longitude = #event.Longitude;
recurrence.Latitude = #event.Latitude;
recurrence.RecurrenceTypeId = #event.RecurrenceTypeId;
recurrence.RecurrenceInterval = #event.RecurrenceInterval;
recurrence.ExcludeWeekends = #event.ExcludeWeekends;
recurrence.CreateDate = #event.CreateDate;
recurrence.UpdateDate = #event.UpdateDate;
recurrence.CreatedBy = #event.CreatedBy;
recurrence.UpdatedBy = #event.CreatedBy;
if (recurrence == null)
{
throw new HttpResponseException(
Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "Error creating recurrence"));
}
var users = db.AspNetUsers.Where(u => #event.UserId.Contains(u.Id));
foreach (var u in users)
recurrence.AspNetUsers.Add(u);
newEvent.Recurrences.Add(recurrence);
db.Events.Add(newEvent);
await db.SaveChangesAsync();
return CreatedAtRoute("DefaultApi", new { id = #event.Id }, newEvent);
}
When i call the post method i get an internal error code 500 and an error message of "{$id=1, Message=An error has occurred}".
Related
I am starting to use AutoMapper. What I want is to do the following one-to-many mapping:
public class EntityEstablishment
{
public int Id { get; set; }
public string Name { get; set; }
public string Location { get; set; }
public int NumberParking { get; set; }
public string EstablishmentImage { get; set; }
public string EstablishmentLogoForDesktop { get; set; }
public string EstablishmentLogoForMobile { get; set; }
public string EstablishmentMap { get; set; }
public int WidthMap { get; set; }
public int HeightMap { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public string Status { get; set; } = "enabled";
public bool AvailableToBooking { get; set; } = true;
public string UserId { get; set; }
public EntityUser User { get; set; }
public List<EntityEquipment> Equipments { get; set; }
public List<EntityBookableArea> BookableAreas { get; set; }
public List<EntityParking> Parkings { get; set; }
public List<EntityBankAccount> BankAccounts { get; set; }
}
public class EntityBookableArea
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public BookableAreaType Type { get; set; }
public int Capacity { get; set; }
public int StoreyNumber { get; set; }
public double ValueHour { get; set; }
public double ValueMidday { get; set; }
public double ValueDay { get; set; }
public double ValueWeek { get; set; }
public double ValueHalfMonth { get; set; }
public double ValueMonth { get; set; }
public double ValueSesion { get; set; }
public double ValueHourByStall { get; set; }
public double ValueMiddayByStall { get; set; }
public double ValueDayByStall { get; set; }
public double ValueWeekByStall { get; set; }
public double ValueHalfMonthByStall { get; set; }
public double ValueMonthByStall { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public string BookableDays { get; set; }
public string BookableClass { get; set; }
public string Status { get; set; }
public double TaxPercentage { get; set; }
public bool IncludeEquipment { get; set; }
public bool IncludeParking { get; set; }
public string Coordinates { get; set; }
public List<EntityBooking> Bookings { get; set; }
public int EstablishmentId { get; set; }
public EntityEstablishment Establishment { get; set; }
}
public class EstablishmentDto
{
public int Id { get; set; }
[Required(ErrorMessage = "El nombre es requerido.")]
public string Name { get; set; }
[Required(ErrorMessage = "La ubicacion es requerida.")]
public string Location { get; set; }
public int NumberParking { get; set; }
public string EstablishmentImage { get; set; }
public string EstablishmentLogoForDesktop { get; set; }
public string EstablishmentLogoForMobile { get; set; }
public string EstablishmentMap { get; set; }
public int WidthMap { get; set; }
public int HeightMap { get; set; }
[Required]
public DateTime StartTime { get; set; }
[Required]
public DateTime EndTime { get; set; }
public string Status { get; set; } = "enabled";
public bool AvailableToBooking { get; set; } = true;
[Required(ErrorMessage = "El Administrador del establecimiento es requerido.")]
public string UserId { get; set; }
public UserDto User { get; set; }
public List<EquipmentDto> Equipments { get; set; }
public List<ParkingDto> Parkings { get; set; }
public List<BookableAreaDto> BookableAreas { get; set; }
public List<BankAccountDto> BankAccounts { get; set; }
}
How can I map the one-to-many relationship to get the information from the establishment with the BookableAreas?
I was trying the following but I get a mapping error - can you guide me on the matter?
Thank you very much for any help.
CreateMap<EntityEstablishment, EstablishmentDto>()
.ForMember(dest => dest.BookableAreas, opt => opt.MapFrom(src => src.BookableAreas))
.ForMember(dest => dest.Parkings, opt => opt.MapFrom(src => src.Parkings))
I want to create a query that will return an AgencyContractData object containing a DocumentDto object, but it may be that the original object does not contain a foreign key on the Document. I can't use ternary operator in an Entity-Framwork LINQ query. How it is possible to implement it (Required that select be converted to sql query)?
var contractList = await query
.Select(contract => new AgencyContractData
{
ContractId = contract.Id,
ContractNumber = contract.ContractNumber,
CustomerId = contract.CustomerId,
CustomerName = contract.CustomerName,
Group = contract.Group,
CommodityType = contract.CommodityType,
SupplierName = contract.SupplierName,
StartDate = contract.StartDate,
EndDate = contract.EndDate,
ExecutionDate = contract.ExecutionDate,
ContractUnit = contract.ContractUnit,
Comment = contract.Comment,
Pricing = contract.Pricing,
SecondaryCustomerName = contract.SecondaryCustomerName,
ContractType = contract.ContractType,
AnnualVolume = contract.AnnualVolume,
Document = new DocumentDto
{
DocumentId = contract.Document.Id,
CounterPartyId = contract.Document.CounterPartyId,
FilePath = contract.Document.FilePath,
DocumentTitle = contract.Document.DocumentTitle,
IsCustomerUpload = contract.Document.IsCustomerUpload,
DocumentBytes = null
},
DocumentName = contract.DocumentName,
ContractNumberInt = contract.ContractNumberInt,
ContractNumberString = contract.ContractNumberString,
MsaBaseNumber = contract.MsaBaseNumber,
NotificationDays = contract.NotificationInDays,
State = contract.State,
CreatedOn = contract.CreatedOn,
CreatedBy = contract.CreatedBy,
ModifiedOn = contract.ModifiedOn,
ModifiedBy = contract.ModifiedBy,
It is the AgencyContract entity:
public class Contract : IEntity<long>
{
public long Id { get; set; }
public string ContractNumber { get; set; }
public long? ContractUnitId { get; set; }
public int? NumPricePeriods { get; set; }
public double? Tolerance { get; set; }
public ContractTypeEnum? ContractType { get; set; }
public ContractTolerancePeriodEnum? ContractTolerancePeriod { get; set; }
public bool IsRelyContract { get; set; }
public int TermsEndNoticeDays { get; set; }
public bool IsProrated { get; set; }
public bool IsContinuation { get; set; }
public long SupplierId { get; set; }
public long? DocumentId { get; set; }
public long? BrokerId { get; set; }
public BillTypeEnum? BillType { get; set; }
public string ExternalId { get; set; }
#region Navigation Properties
public virtual Supplier Supplier { get; set; }
public virtual Broker Broker { get; set; }
public virtual ContractUnit ContractUnit { get; set; }
public virtual Account Account { get; set; }
public virtual List<UsnAccountToContract> UsnAccountToContracts { get; set; }
public virtual List<ProviderLookup> ProviderLookups { get; set; }
public virtual List<ContractNotification> ContractNotifications { get; set; }
public virtual List<ContractVolume> ContractVolumes { get; set; }
public virtual Document Document { get; set; }
#endregion
And I want to make a AgencyContractData object using Select:
public class AgencyContractData
{
public int? AnnualVolume { get; set; }
public string Comment { get; set; }
public AgencyCommodityTypeEnum CommodityType { get; set; }
public long ContractId { get; set; }
public string ContractNumber { get; set; }
public long? ContractNumberInt { get; set; }
public string ContractNumberString { get; set; }
public int? ContractReportLevelByGlobalSearch { get; set; }
public AgencyContractTypeEnum ContractType { get; set; }
public AgencyContractUnitEnum ContractUnit { get; set; }
public Guid? CreatedBy { get; set; }
public DateTime? CreatedOn { get; set; }
public long? CustomerId { get; set; }
public string CustomerName { get; set; }
public string DocumentName { get; set; }
public DocumentDto Document { get; set; }
public DateTime? EndDate { get; set; }
public DateTime ExecutionDate { get; set; }
public string Group { get; set; }
public List<AgencyLocationData> Locations { get; set; }
public Guid? LockedBy { get; set; }
public DateTime? LockedOn { get; set; }
public string Md5Hash { get; set; }
public Guid? ModifiedBy { get; set; }
public DateTime? ModifiedOn { get; set; }
public string MsaBaseNumber { get; set; }
public int? NotificationDays { get; set; }
public DateTime? NotificationSentOn { get; set; }
public string Pricing { get; set; }
public string SecondaryCustomerName { get; set; }
public int Sites { get; set; }
public DateTime StartDate { get; set; }
public string State { get; set; }
public string Status { get; set; }
public string SupplierName { get; set; }
I am trying to insert a data in my local database (SQLited Database) using InsertAsync. But I keep getting this error.
sqlite.sqliteexception: constraint at sqlite.preparedsqlliteinsertcommand.executenonquery
How can I fix and avoid this in the future? Below is my sample code.
var db = DependencyService.Get<ISQLiteDB>();
var conn = db.GetConnection();
try
{
var caf_insert = new CAFTable
{
CAFNo = caf,
EmployeeID = employeenumber,
CAFDate = DateTime.Parse(date),
CustomerID = retailercode,
StartTime = DateTime.Parse(starttime),
EndTime = DateTime.Parse(endtime),
Photo1 = photo1url,
Photo2 = photo2url,
Photo3 = photo3url,
Video = videourl,
GPSCoordinates = actlocation,
Remarks = remarks,
OtherConcern = otherconcern,
RecordLog = recordlog,
LastUpdated = DateTime.Parse(current_datetime)
};
await conn.InsertOrReplaceAsync(caf_insert);
}
catch (Exception ex)
{
Crashes.TrackError(ex);
}
Here is the CAF Table
[Table("tblCaf")]
public class CAFTable
{
[PrimaryKey, MaxLength(50)]
public string CAFNo { get; set; }
[MaxLength(50)]
public string EmployeeID { get; set; }
public DateTime CAFDate { get; set; }
[MaxLength(50)]
public string CustomerID { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public string Photo1 { get; set; }
public string Photo2 { get; set; }
public string Photo3 { get; set; }
public string Video { get; set; }
public string MobilePhoto1 { get; set; }
public string MobilePhoto2 { get; set; }
public string MobilePhoto3 { get; set; }
public string MobileVideo { get; set; }
[MaxLength(2000)]
public string Remarks { get; set; }
[MaxLength(2000)]
public string OtherConcern { get; set; }
[MaxLength(2000)]
public string GPSCoordinates { get; set; }
[MaxLength(100)]
public string RecordLog { get; set; }
public DateTime LastSync { get; set; }
public DateTime LastUpdated { get; set; }
public int Existed { get; set; }
public int Deleted { get; set; }
public int ThisSynced { get; set; }
public int Media1Synced { get; set; }
public int Media2Synced { get; set; }
public int Media3Synced { get; set; }
public int Media4Synced { get; set; }
}
Make sure the value of caf in your code, that you're trying to insert, does not already exist in the table.
I have a table in my view that a model is typed to it. However, now I need to change that model to a ViewModel (so I can Union other models on to it but one step at a time). Currently, I query my model (which works) but now I need to figure out how to convert that IEnumerable to bind it to the ViewModel (in this case, it is searchResultViewModel). I gathered what i would need to loop through each line in the IEnumerable and bind it individually (that is what the foreach loop is, me trying that) but I need to convert it back in to an 'IEnumerable'. How do I bind the IEnumerable to my ViewModel but as an 'IEnumerable'? I cannot find anyone else asking a question like this.
[HttpPost]
public ActionResult SearchResult(SearchOrders searchOrders)
{
var orderList = uni.Orders;
var model = from order in orderList
select order;
if (searchOrders.SearchStartDate.HasValue)
{
model = model.Where(o => o.OrderDate >= searchOrders.SearchStartDate);
}
if (searchOrders.SearchEndDate.HasValue)
{
model = model.Where(o => o.OrderDate <= searchOrders.SearchEndDate);
}
if (searchOrders.SearchAmount.HasValue)
{
model = model.Where(o => o.Total == searchOrders.SearchAmount);
}
var searchResultViewModel = new SearchResultViewModel();
foreach (var record in model)
{
searchResultViewModel.OrderNumber = record.OrderId;
searchResultViewModel.PaymentName = record.PaymentFullName;
searchResultViewModel.OrderDate = record.OrderDate;
searchResultViewModel.Amount = record.Total;
}
return View(model);
}
Here is my SearchOrders Model:
namespace MicrositeInfo.WebUI.Models
{
public class SearchOrders
{
public DateTime? SearchStartDate { get; set; }
public DateTime? SearchEndDate { get; set; }
public decimal? SearchAmount { get; set; }
}
}
and here is my SearchResultViewModel:
namespace MicrositeInfo.WebUI.Models
{
public class SearchResultViewModel
{
public int OrderNumber { get; set; }
public string PaymentName { get; set; }
public DateTime OrderDate { get; set; }
public decimal Amount { get; set; }
}
}
and the model that is being queried is the order model:
namespace MicrositeInfo.Model
{
[Table("Order")]
public class Order
{
public int OrderId { get; set; }
public string SelectedSession { get; set; }
public string StudentCity { get; set; }
public string StudentExtension { get; set; }
public string StudentFullName { get; set; }
public string StudentPhone { get; set; }
public string StudentPin { get; set; }
public string StudentState { get; set; }
public string StudentStreet01 { get; set; }
public string StudentStreet02 { get; set; }
public string StudentUniversityId { get; set; }
public string StudentZip { get; set; }
public string PaymentCity { get; set; }
public string PaymentCreditCardExpiration { get; set; }
public string PaymentCreditCardNumber { get; set; }
public string PaymentCreditCardSecurityCode { get; set; }
[Display(Name="Payment Name")]
public string PaymentFullName { get; set; }
public string PaymentState { get; set; }
public string PaymentStreet01 { get; set; }
public string PaymentStreet02 { get; set; }
public string PaymentZip { get; set; }
[Display(Name = "Package Id")]
[ForeignKey("Product")]
public int ProductId { get; set; }
public virtual Product Product { get; set; }
public decimal Price { get; set; }
public decimal Tax { get; set; }
public decimal Total { get; set; }
[Display(Name = "Order Date")]
public DateTime OrderDate { get; set; }
public string OrderIp { get; set; }
public string StudentEmail { get; set; }
public string PaymentId { get; set; }
public int Status { get; set; }
public string ApprovalCode { get; set; }
public decimal Shipping { get; set; }
public string STCITrackingClassCode { get; set; }
}
}
I have the following datamodel and its associated model classes. I have been removing dependencies to get it right, but I keep on getting this error.
Datamodel
I can't find out why there is a cascading path in the model. I am afraid I will not be able to reduce the dependencies.
Model Classes
public class DataFormat
{
public int DataFormatID { get; set; }
[Display (Name = "Data Format Name")]
[Remote("DuplicateFormatName", "DataFormats", HttpMethod = "POST", ErrorMessage = "Data Format Name already Exists")]
public string FormatName { get; set; }
[Display (Name = "Data Format Type")]
public string FormatType { get; set; }
[Display (Name = "Precision Digits")]
public string PrecisionDigits { get; set; }
[Display (Name = "Scaling Digits")]
public string ScalingDigits { get; set; }
[Display (Name = "Description in German")]
public string DescriptionDE { get; set; }
[Display (Name = "Description in English")]
public string DescriptionEN { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime ModifiedOn { get; set; }
public string CreatedBy { get; set;}
public string ModifiedBy { get; set; }
public virtual ICollection<TcSet> TcSets { get; set; }
}
public class Lsystem
{
public int LsystemID { get; set; }
[Display (Name = "System Name") ]
[Remote("DuplicateSystemName", "Lsystems", HttpMethod = "POST", ErrorMessage = "System Name already Exists")]
public string LsystemName { get; set; }
[Display (Name = "Material Number")]
public string MaterialNumber { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime ModifiedOn { get; set; }
public string CreatedBy { get; set; }
public string ModifiedBy { get; set; }
[Display(Name = "Description in English")]
public string DescriptionEN { get; set; }
[Display(Name = "Description in German")]
public string DescriptionDE { get; set; }
public int LsystemFamilyID { get; set; }
public virtual LsystemFamily LsystemFamily { get; set; }
public virtual ICollection<Option> Options { get; set; }
}
public class LsystemFamily
{
public int LsystemFamilyID { get; set; }
[Display (Name = "Family Name")]
[Remote("DuplicateFamilyName","LsystemFamilies",HttpMethod = "POST",ErrorMessage= "System Family Name already Exists")]
public string FamilyName { get; set; }
public int LsystemCount { get; set; }
[Display ( Name = "Description in English")]
public string DescriptionEN { get; set; }
[Display (Name = "Description in German")]
public string DescriptionDE { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime ModifiedOn { get; set; }
public string CreatedBy { get; set; }
public string ModifiedBy { get; set; }
public virtual ICollection<Lsystem> Lsystems { get; set; }
}
public class Option
{
public int OptionID { get; set;}
[Display (Name = "Option Type")]
public string OptionName { get; set; }
[Display (Name ="Description in English")]
public string DescriptionEN { get; set; }
[Display(Name = "Description in German")]
public string DescriptionDE { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime ModifiedOn { get; set; }
public string CreatedBy { get; set; }
public string ModifiedBy { get; set; }
public int TechnicalCharacteristicID { get; set; }
public int LsystemID { get; set; }
public virtual ICollection<OptionValue> OptionValues { get; set; }
public virtual TechnicalCharacteristic TechnicalCharacteristic { get; set; }
public virtual Lsystem Lsystem { get; set; }
// public virtual ICollection< SetValue> SetValue { get; set; }
}
public class OptionValue
{
public int OptionValueID { get; set; }
[Display(Name = "Option Value")]
public string OptionVal { get; set; }
public int OptionID { get; set; }
// public int SetValueID { get; set; }
public virtual Option Option { get; set; }
public virtual ICollection< SetValue> SetValue { get; set; }
}
public class SetValue
{
public int SetValueID { get; set; }
[Display(Name = "Value")]
public string Value { get; set; }
[Display(Name="Internal")]
public bool Status { get; set; }
//public int LsystemID { get; set; }
//public int OptionID { get; set; }
public int TcSetID { get; set; }
public int OptionValueID { get; set; }
//public virtual Lsystem Lsystem { get; set; }
//public virtual Option Option { get; set; }
public virtual OptionValue OptionValue { get; set; }
public virtual TcSet TcSet { get; set; }
}
public class TcSet
{
public int TcSetID { get; set; }
[Display (Name = "Technical characteristic Property name")]
public string SetName { get; set; }
[Display(Name = "PhysicalUnit")]
public string PhysicalUnit { get; set; }
[Display (Name = "Data Usage")]
public DataUsage DataUsage { get; set; }
[Display (Name = "Data Status")]
public DataStatus DataStatus { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime ModifiedOn { get; set; }
[Display (Name = "Description in German")]
public string DescriptionDE { get; set; }
[Display (Name = "Description in English")]
public string DescriptionEN { get; set; }
public string CreatedBy { get; set; }
public string ModifiedBy { get; set; }
public int TechnicalCharacteristicID { get; set; }
public int DataFormatID { get; set; }
public virtual ICollection<SetValue> SetValues { get; set; }
public virtual DataFormat DataFormat { get; set; }
public virtual TechnicalCharacteristic TechnicalCharacteristic { get; set; }
}
public class TechnicalCharacteristic
{
public int TechnicalCharacteristicID { get; set; }
[Display (Name = "Technical Characteristic Name")]
public string TCName { get; set; }
[Display (Name = "Description in English")]
public string DescriptionEN { get; set; }
[Display (Name = "Description in German")]
public string DescriptionDE { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime ModifiedOn { get; set; }
public string CreatedBy { get; set; }
public string ModifiedBy { get; set; }
public virtual ICollection<TcSet> TcSets { get; set; }
//public virtual ICollection<Option> Options { get; set; }
}
Now my error is between the tables Options and technicalCharacteristics. I had the error previosly with LSystem and SetVal & Options.
What can be the workaround to get the task right?
I have not tried fluent APIs.
Here is another way you can do the same AND have a technicalChareristic to be required. I did this last week with one of my own models. Sorry it toook so long to come up with a reply. (Do the same with the other files.)
In your Context file override the following method...
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Option>()
.HasRequired(x => x.TechnicalCharacteristic)
.WithMany(y => y.Options)
.HasForeignKey(a => a.TechnicalCharacteristicID)
.WillCascadeOnDelete(false);
base.OnModelCreating(modelBuilder);
}
Where the models are...
public class Option
{
public int OptionID { get; set; }
[Display(Name = "Option Type")]
public string OptionName { get; set; }
[Display(Name = "Description in English")]
public string DescriptionEN { get; set; }
[Display(Name = "Description in German")]
public string DescriptionDE { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime ModifiedOn { get; set; }
public string CreatedBy { get; set; }
public string ModifiedBy { get; set; }
public int LsystemID { get; set; }
public virtual ICollection<OptionValue> OptionValues { get; set; }
public int TechnicalCharacteristicID { get; set; }
public virtual TechnicalCharacteristic TechnicalCharacteristic { get; set; }
public virtual Lsystem Lsystem { get; set; }
// public virtual ICollection< SetValue> SetValue { get; set; }
DateTime d = new DateTime();
}
public class TechnicalCharacteristic
{
public int TechnicalCharacteristicID { get; set; }
[Display(Name = "Technical Characteristic Name")]
public string TCName { get; set; }
[Display(Name = "Description in English")]
public string DescriptionEN { get; set; }
[Display(Name = "Description in German")]
public string DescriptionDE { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime ModifiedOn { get; set; }
public string CreatedBy { get; set; }
public string ModifiedBy { get; set; }
public virtual ICollection<TcSet> TcSets { get; set; }
public virtual ICollection<Option> Options { get; set; }
}
I hope this helps.
I believe your error is coming because EntityFramework cannot handle the null state of your TechnicalCharacteristicID in the Option class. If you have no problem in TechnicalCharacteristic being null, do the following in your option class. It should get rid of your error:
public int? TechnicalCharacteristicID { get; set; }
that is, your option class will become...
public class Option
{
public int OptionID { get; set; }
[Display(Name = "Option Type")]
public string OptionName { get; set; }
[Display(Name = "Description in English")]
public string DescriptionEN { get; set; }
[Display(Name = "Description in German")]
public string DescriptionDE { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime ModifiedOn { get; set; }
public string CreatedBy { get; set; }
public string ModifiedBy { get; set; }
public int LsystemID { get; set; }
public virtual ICollection<OptionValue> OptionValues { get; set; }
public int? TechnicalCharacteristicID { get; set; }
public virtual TechnicalCharacteristic TechnicalCharacteristic { get; set; }
public virtual Lsystem Lsystem { get; set; }
// public virtual ICollection< SetValue> SetValue { get; set; }
}
Do the same with other errant tables. I hope this answers your question! Good luck.