MVC4 - Server Error in '/' Application - entity-framework

I build a simple model. The reason StartDate is DateTime2 is because previously it gave me an error when i tried to have the DateTime.
public class Auction
{
[Key]
public string Id { get; set; }
[Required]
public string Title { get; set; }
public string Description { get; set; }
[Column(TypeName = "DateTime2")]
[Display(Name = "StartTime")]
public DateTime StartTime { get; set; }
[Column(TypeName = "DateTime2")]
public DateTime EndTime { get; set; }
public int StartPrice { get; set; }
public int CurrentPrice { get; set; }
public string category { get; set; }
public virtual Collection<Bid> Bids { get; private set; }
public int BidCount
{
get { return Bids.Count; }
}
public Auction()
{
Bids = new Collection<Bid>();
}
and i created a create() function in controller.
[HttpPost]
public ActionResult create(Auction auction)
{
var categoryList = new SelectList(new[] { "auto", "elec", "games", "Home" });
ViewBag.categoryList = categoryList;
auction.StartTime= DateTime.Now;
auction.EndTime = DateTime.Now.AddDays(7);
if (ModelState.IsValid)
{
//Save the form
var db = new AuctionsDataContext();
db.Auctions.Add(auction);
db.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
I get this error when i try to save changes:
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

Related

System.NullReferenceException: 'Object reference not set to an instance of an object.' - In .NET Core 3.1

I am making a BookEvent app using ASP.NET Core 3.1 MVC. I am facing this error System.NullReferenceException: 'Object reference not set to an instance of an object.' Microsoft.AspNetCore.Mvc.Razor.RazorPage<TModel>.Model.get returned null.
How can I fix it?
I am trying to display all created events at the home page.
File HomeController.cs
[HttpGet]
public IActionResult AllEvents()
{
var result = _eventAppService.GetAllEvent();
var details = _mapper.Map<EventViewModel>(result.Data);
if (result.IsSuccess)
{
this._logger.LogInformation(result.MainMessage.Text);
}
else
{
Message = $"About page visited at {DateTime.UtcNow.ToLongTimeString()}";
this._logger.LogError(Message);
return View("Index");
}
return View(details);
}
File EventAppServices.cs
public OperationResult<IEnumerable<EventDTO>> GetAllEvent()
{
IEnumerable<Event> eventList = _eventRepository.Get(x => x.IsActive).ToList<Event>();
List<EventDTO> eventDTOList = new List<EventDTO>();
eventDTOList = _mapper.Map<IEnumerable<Event>, List<EventDTO>>(eventList);
Message message = new Message(string.Empty, "Return Successfully");
var eventslist = new OperationResult<IEnumerable<EventDTO>>(eventDTOList, true, message);
return eventslist;
}
File Index.cshtml
File EventViewModel.cs
public class EventViewModel : ViewModel
{
[Display(Name = "Title")]
[Required]
public string Title { get; set; }
[Display(Name = "Date")]
[DataType(DataType.Date)]
[Required]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public string Date { get; set; }
[Display(Name = "Location")]
[Required]
public string Location { get; set; }
[Display(Name = "Start Time")]
[Required]
[DataType(DataType.Time)]
[DisplayFormat(DataFormatString = "{0:HH:mm}", ApplyFormatInEditMode = true)]
public string StartTime { get; set; }
[Required]
public string Type { get; set; }
public EventType eventTypes;
[Display(Name = "Duration In Hours")]
[Range(0, 4)] public virtual ICollection<UserEvent> UserEvent { get; set; }
public int? Duration { get; set; }
[MaxLength(50)]
public string Description { get; set; }
[MaxLength(500)]
[Display(Name = "Other Details")]
public string OtherDetails { get; set; }
[Display(Name = "Invite Others")]
public string InviteByEmail { get; set; }
public int Count { get; set; }
}
The problem is in your mapping OperationResult<IEnumerable<EventDTO>> to IEnumerable. Make sure you map it correctly.

.NET5.0 Ensure that the return type can be mapped by the current provider

Model:
public partial class FN_Result
{
public string UserImage { get; set; }
public string UserName { get; set; }
public string Title { get; set; }
public int messageId { get; set; }
public int SenderId { get; set; }
public int ReceiverId { get; set; }
public string MessageText { get; set; }
public bool MessageStatus { get; set; }
public bool IsAdmin { get; set; }
public bool IsClinician { get; set; }
public string CreatedOn { get; set; }
public int RowNum { get; set; }
}
Constructor and variable declaration:
private readonly IDbConnection db;
public DbContext(DbContextOptions<DbContext> options, IConfiguration configuration)
: base(options)
{
this.Configuration = configuration;
this.db = new SqlConnection(this.Configuration.GetConnectionString("PortalDb"));
}
We have the following DbFunction in an MVC project .NET 5.0
[DbFunction("namespace", "FN_Name")]
public async Task<IEnumerable<FN_Result>> FN_MethodName(int id)
{
var parameters = new DynamicParameters();
parameters.Add("#id", id);
return await this.db.QueryAsync<FN_Result>("[namespace].[FN_Name](#id)", parameters, commandType: CommandType.Text);
}
IEnumerable<FN_Result> is indeed the return type of db.QueryAsync<FN_Result>
However it's throwing the following error message: Message=The DbFunction 'dbPortalContext.FN_Name([System.Int32, System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e])' has an invalid return type 'Task<IEnumerable<FN_Result>>'. Ensure that the return type can be mapped by the current provider.
We have also tried converting it into a List, to no avail

Entity Framework always adds two records in the tables

I'm implementing an ASP.NET Core 3.1 app. I have implemented following code to insert record in SQL Server database via EF Core but each time I save data, it inserts two records in PersonRequester and Requester table. I appreciate if anyone suggests me how I can prevent reinserting records.
Requester ap = new Requester();
ap.Address = RequesterViewModel.Requestervm.Address;
ap.RequesterType = RequesterViewModel.Requestervm.RequesterType;
ap.Description = RequesterViewModel.Requestervm.Description;
ap.Name = RequesterViewModel.Requestervm.Name;
var pa = new PersonRequester()
{
BirthCertificateNo = RequesterViewModel.personRequestervm.BirthCertificateNo,
IssuePlace = RequesterViewModel.personRequestervm.IssuePlace,
NationalCode = RequesterViewModel.personRequestervm.NationalCode,
Requester = ap
};
using (var context = new DBContext())
{
context.PersonRequester.Attach(pa);
try
{
context.SaveChanges();
}
catch (Exception e)
{
throw e;
}
}
public partial class Requester
{
public Requester()
{
PersonRequester = new HashSet<PersonRequester>();
}
public int RequesterId { get; set; }
public int RequesterType { get; set; }
public string Address { get; set; }
public string Description { get; set; }
public string Name { get; set; }
public virtual EntityType RequesterTypeNavigation { get; set; }
public virtual ICollection<PersonRequester> PersonRequester { get; set; }
}
public partial class PersonRequester
{
public int RequesterId { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public int RequesterType { get; set; }
public string NationalCode { get; set; }
public string BirthCertificateNo { get; set; }
public string IssuePlace { get; set; }
public virtual Requester Requester { get; set; }
public virtual EntityType RequesterTypeNavigation { get; set; }
}

Entity Framework not saving update for just one property on just one Entity Type

I am using ASP.Net Core MVC and Entity Framework Core in Visual Studio 2017.
We are using a pretty straight forward Repository Pattern.
I'm eight months into this project and this is the first time I am having this strange problem on this one property on this one entity getting saved to the Database on SaveChanges after UpdateChanges.
So here is the flow.
1) I have a Create controller action to save a new entity called Recommendation.
The Recommendation has a parent entity called finding.
When I create a new recommendation I have to update the status on the parent finding. Also the Finding entity has a parent Entity called Audit.
When I edit the finding status I also have to update the audit status.
Here is some code for this.
[HttpPost]
public IActionResult Create(CreateIntRecommendationVM createIntRecommendationVM)
{
int findingId = createIntRecommendationVM.Finding.FindingId;
Finding finding = _findingRepo.Findings
.Include(f => f.Audit)
.Where(f => f.FindingId == findingId)
.FirstOrDefault();
if (RecModelStateIsValid(ModelState))
{
ClaimsPrincipal user = HttpContext.Request.HttpContext.User;
short staffId = short.Parse(user.Claims.Single(c => c.Type == "StaffId").Value);
Recommendation recommendation = createIntRecommendationVM.Recommendation;
recommendation.RecFindingId = findingId;
#region Get Recommendation Number
recommendation.RecCd = GetRecommendationNumber(findingId);
#endregion
recommendation.RecStatusId = 10;
recommendation.RecStaffId = staffId;
recommendation.RecLastUpdateDt = DateTime.Now;
_recommendationRepo.Add(recommendation);
_recommendationRepo.SaveChanges();
bool unresolvedFinding = false;
bool unresolvedAudit = false;
int? oldFindingStatus = finding.FindingStatusId;
if (finding.FindingStatusId != 10)
{
finding.FindingStatusId = 10;
unresolvedFinding = true;
}
if (oldFindingStatus != 10 && finding.Audit.StatusID != 10)
{
finding.Audit.StatusID = 10;
unresolvedAudit = true;
}
_findingRepo.Update(finding);
_findingRepo.SaveChanges();
When I run in debug mode and put a break point and inspect while I am stepping through, I am definately setting finding.FindingStatusId to 10 and finding.Audit.StatusID to 10.
_findingRepo.Update(finding);
hits this repo:
public class FindingRepository : IFindingRepository
{
private ApplicationDbContext context;
public FindingRepository(ApplicationDbContext ctx)
{
context = ctx;
}
public IQueryable<Finding> Findings => context.Findings;
public Finding Get(int id)
{
Finding finding = context.Findings.Find(id);
return finding;
}
public void Add(Finding finding)
{
context.Findings.Add(finding);
}
public void Update(Finding finding)
{
context.Findings.Update(finding);
}
public void Delete(int id)
{
context.Database.ExecuteSqlCommand("sp_delete_finding_int #finding_id = {0}", id);
}
public void SaveChanges()
{
context.SaveChanges();
}
}
So here is the weird part.
finding.Audit.StatusID is getting updated in the DB.
finding.FindingStatusId is not.
So for the entity, "finding" that I am sending to the repo's Update method, the "FindingStatusId" for the entity being updated is not getting saved.
But, the "finding" entity's parent, "Audit", the "StatusID" is getting saved.
I can't for the life of me figure out what is going on here.
For completeness I'll post the Finding and Audit Entity Models.
[Table("finding")]
public class Finding
{
private string _findingText;
[Key]
[Column("finding_id")]
public int FindingId { get; set; }
[Column("finding_audit_id")]
public int FindingAuditId { get; set; }
[Column("finding_cd")]
[Display(Name = "Finding #")]
[StringLength(15)]
public string FindingCd { get; set; }
[Column("finding_tx")]
[Required(ErrorMessage = "Description Required")]
[StringLength(7000)]
public string FindingText
{
get
{
return _findingText;
}
set
{
_findingText = value?.Trim();
}
}
[Column("finding_page_cd")]
[StringLength(100)]
public string FindingPageCd { get; set; }
[Column("finding_joint_cd")]
public string FindingJointCd { get; set; }
[Column("finding_compliance_tx")]
[StringLength(20)]
public string FindingComplianceText { get; set; }
[Column("finding_prior_year_cd")]
[Display(Name = "Repeat Finding")]
public string FindingPriorYearCd { get; set; }
[Column("finding_decision_cd")]
public string FindingDecisionCd { get; set; }
[Column("finding_request_decision_cd")]
public string FindingRequestDecisionCd { get; set; }
[Column("finding_decision_ogc_concur_cd")]
public string FindingDecisionOgcConcurCd { get; set; }
[Column("finding_pdl_id")]
public int? FindingPdlId { get; set; }
[Display(Name = "Significant")]
[Column("finding_significant_cd")]
public string FindingSignificantCd { get; set; }
[Column("finding_on_stay_cd")]
public string FindingOnStayCd { get; set; }
[Column("finding_stay_request_cd")]
public string FindingStayRequestCd { get; set; }
[Column("finding_last_update_dt")]
public DateTime FindingLastUpdateDate { get; set; }
[Column("finding_update_staff_id")]
public short? FindingUpdateStaffId { get; set; }
[Column("finding_cd_org")]
public string FindingCdOrg { get; set; }
[NotMapped]
public string RepeatingYearsDisplayList
{
get
{
if (RepeatingYears?.Count > 0)
{
string repeatingYears = string.Empty;
RepeatingYears.ForEach(ry =>
repeatingYears += $"{ry.FindingFyCd}, ");
return repeatingYears.Remove(repeatingYears.Length - 2);
}
return string.Empty;
}
}
#region Navigation Properties
[Column("finding_finding_type_id")]
public short? FindingTypeId { get; set; }
[ForeignKey("FindingTypeId")]
public FindingType FindingType { get; set; }
[Column("finding_status_id")]
public int? FindingStatusId { get; set; }
[ForeignKey("FindingStatusId")]
public Status FindingStatus { get; set; }
public List<FindingFiscalYear> RepeatingYears { get; set; }
public List<Recommendation> Recommendations { get; set; }
[ForeignKey("FindingAuditId")]
public Audit Audit { get; set; }
#endregion
}
[Table("audit")]
public class Audit
{
private string _auditAcnCd;
private string _title;
private string _summary;
[Key]
[Column("audit_id")]
public int AuditID { get; set; }
[Required(ErrorMessage = "ACN Required")]
[Display(Name="ACN:")]
[Column("audit_acn_cd")]
public string AuditAcnCd
{
get
{
return _auditAcnCd;
}
set
{
_auditAcnCd = value?.Trim();
}
}
[Required(ErrorMessage = "Title Required")]
[Display(Name = "Title:")]
[Column("audit_report_title_tx")]
public string Title
{
get
{
return _title;
}
set
{
_title = value?.Trim();
}
}
[Required(ErrorMessage = "Issuer Required")]
[Display(Name="Issuer:")]
[Column("audit_issuer_tx")]
public string Issuer { get; set; }
[Display(Name = "Sensitive Designation")]
[Column("audit_sensitive_cd")]
public string AuditSensitiveCode { get; set; }
[Display(Name = "Alternative Product")]
[Column("audit_alternate_product_cd")]
public string AuditAlternateProductCode { get; set; }
[RegularExpression("([1-9][0-9]*)", ErrorMessage = "Priority must be a number.")]
[Display(Name = "Priority:")]
[Column("audit_priority_cd")]
public short? Priority { get; set; }
[StringLength(maximumLength: 1000,ErrorMessage = "Max Length: 1000")]
[Display(Name = "Summary:")]
[Column("audit_summary_tx")]
public string Summary
{
get
{
return _summary;
}
set
{
_summary = value?.Trim();
}
}
[Column("audit_gao_contact_tx")]
[Display(Name = "GAO Contact:")]
[StringLength(maximumLength: 200, ErrorMessage = "Max Length: 200")]
public string AuditGaoContactText { get; set; }
[Column("audit_gao_job_cd")]
[Display(Name = "GAO Job Code:")]
[StringLength(maximumLength: 200, ErrorMessage = "Max Length: 30")]
public string AuditGaoJobCode { get; set; }
[Display(Name = "Lead Office:")]
[Column("audit_lead_office_id")]
public short? LeadOfficeID { get; set; }
#region Navigation Properties
[Required(ErrorMessage = "Audit Type Required.")]
[Display(Name = "Audit Type:")]
[Column("audit_audit_type_id")]
public short AuditTypeID { get; set; }
[Display(Name = "Audit Type:")]
public AuditType AuditType { get; set; }
[Column("audit_status_id")]
public int StatusID { get; set; }
public Status Status { get; set; }
[Required(ErrorMessage = "Office is Required.")]
[Display(Name = "Offices:")]
[Column("audit_office_id")]
public short? OfficeID { get; set; }
public Office Office { get; set; }
[ForeignKey("AuditID")]
public External External { get; set; }
public IEnumerable<AuditLog> AuditLogs { get; set; }
public IEnumerable<Finding> Findings { get; set; }
public IEnumerable<Assignment> Assignments { get; set; }
[Column("audit_update_staff_id")]
public short UpdateStaffID { get; set; }
[Column("audit_oig_manager_id")]
[Display(Name = "OIG Audit Manager:")]
public short? OigAuditManagerId { get; set; }
[Display(Name = "OIG Audit Manager:")]
[ForeignKey("OigAuditManagerId")]
public Staff OigAuditManager { get; set; }
[Column("audit_fsa_office_id")]
[Display(Name = "FSA Audit Lead:")]
public int? FsaLeadOfficeId { get; set; }
[Display(Name = "FSA Audit Lead:")]
[ForeignKey("FsaLeadOfficeId")]
public FSAOffice FsaLeadOffice { get; set; }
[ForeignKey("LeadOfficeID")]
public Office LeadOffice { get; set; }
#endregion
}
Well just as I was hoping I opened it back up this morning, started fresh, and it's working.
Ivan, I believe you are right. You don't need to call Update for Entity Framework. I've noticed this before if I forget the Update statement.
And if you don't need to you are making a call to update in the repo for no reason.
I was resetting scenarios by hand in the DB to test this over and over. Something must have gotten corrupt.
But all the code above is working if it helps anyone.

BreezeJs: Update to new metadata from changed BreezeController

I've changed and added some properties to my server-side classes but can't get the updated data in my breeze/angular app. The added fields stay blank instead of showing the value. I also can't create an entity that i've added. (error). How can i update the metadata in my breeze/angular app to use the latest version? I've tried to fetch the metadata, but getting the message that it already was fetched.
Breeze: Unable to locate a 'Type' by the name: 'New Class'. Be sure to execute a query or call fetchMetadata first
Update (More Info)
I've created a child class related to my Product class. It's called ProductStockItem, so a Product has many ProductStockItems.
ProductStockItem: (new Class)
public class ProductStockItem
{
public int Id { get; set; }
public int ProductId { get; set; }
public string Size { get; set; }
public int Quantity { get; set; }
public bool UseStockQuantity { get; set; }
public decimal PriceAdjustment { get; set; }
public DateTime? DateAvailable { get; set; }
public int DisplayOrder { get; set; }
public bool Deleted { get; set; }
public State State { get; set; }
public DateTime? DateChanged { get; set; }
public DateTime? DateCreated { get; set; }
public virtual Product Product { get; set; }
}
Product:
public class Product
{
private ICollection<ProductCategory> _productCategories;
private ICollection<ProductManufacturer> _productManufacturers;
private ICollection<ProductPicture> _productPictures;
private ICollection<ProductSpecificationAttribute> _productSpecificationAttributes;
private ICollection<ProductStockItem> _productStockItems;
public int Id { get; set; }
public ProductType ProductType { get; set; }
public int ParentGroupedProductId { get; set; }
public int ManufacturerSizeId { get; set; }
public bool VisibleIndividually { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string MetaTitle { get; set; }
public string MetaDescription { get; set; }
public int DisplayOrder { get; set; }
public bool LimitedToStores { get; set; }
public string Sku { get; set; }
public string UniqueCode { get; set; }
public decimal Price { get; set; }
public decimal OldPrice { get; set; }
public decimal? SpecialPrice { get; set; }
public DateTime? SpecialPriceStartDateTimeUtc { get; set; }
public DateTime? SpecialPriceEndDateTimeUtc { get; set; }
public decimal DiscountPercentage { get; set; }
public bool HasTierPrices { get; set; }
public bool HasStock { get; set; }
public TaxRate TaxRate { get; set; }
public bool SyncToShop { get; set; }
public bool Deleted { get; set; }
public bool Locked { get; set; }
public State State { get; set; }
public DateTime? DateChanged { get; set; }
public DateTime? DateCreated { get; set; }
public virtual ICollection<ProductCategory> ProductCategories
{
get { return _productCategories ?? (_productCategories = new List<ProductCategory>()); }
protected set { _productCategories = value; }
}
public virtual ICollection<ProductManufacturer> ProductManufacturers
{
get { return _productManufacturers ?? (_productManufacturers = new List<ProductManufacturer>()); }
protected set { _productManufacturers = value; }
}
public virtual ICollection<ProductPicture> ProductPictures
{
get { return _productPictures ?? (_productPictures = new List<ProductPicture>()); }
protected set { _productPictures = value; }
}
public virtual ICollection<ProductSpecificationAttribute> ProductSpecificationAttributes
{
get { return _productSpecificationAttributes ?? (_productSpecificationAttributes = new List<ProductSpecificationAttribute>()); }
protected set { _productSpecificationAttributes = value; }
}
public virtual ICollection<ProductStockItem> ProductStockItems
{
get { return _productStockItems ?? (_productStockItems = new List<ProductStockItem>()); }
protected set { _productStockItems = value; }
}
}
Product request:
http://testdomain.local/breeze/DataContext/Products?$filter=Id%20eq%201029&$orderby=Id&$expand=ProductStockItems&
[{"$id":"1","$type":"Erp.Models.ErpModel.Catalog.Product, Erp.Models.ErpModel","Id":1029,"ProductType":"SimpleProduct","ParentGroupedProductId":0,"ManufacturerSizeId":2767,"VisibleIndividually":false,"Name":"Jako Ballenzak Kids - Ash / Action Green","ExtraName":null,"Description":"• Aangenaam functioneel materiaal\nmet moderne oppervlaktestructuur\nvoor de hoogste normen\n• Zeer goede klimaateigenschappen\ndoor actief ademend Twill-Polyester\n• Rekbaar, vormvast en sneldrogend\n\nPolyester-Twill\n100% Polyester,\nbinnenvoering: 100% Polyester","MetaTitle":null,"MetaDescription":null,"DisplayOrder":1,"LimitedToStores":false,"Sku":"9894","UniqueCode":"6_9","Price":34.96,"OldPrice":49.95,"SpecialPrice":null,"SpecialPriceStartDateTime":null,"SpecialPriceEndDateTime":null,"DiscountPercentage":0.00,"HasTierPrices":true,"HasStock":false,"TaxRate":"Tax_21","SyncToShop":true,"Deleted":false,"Locked":false,"State":"Changed","DateChanged":"2014-02-28T10:35:47.733","DateCreated":"2014-02-28T10:35:47.733","ProductCategories":[],"ProductManufacturers":[],"ProductPictures":[],"ProductSpecificationAttributes":[],"ProductStockItems":[]}]
Metadata request:
http://testdomain.local/breeze/DataContext/Metadata
Error Client Side: (create new productStockItem)
Unable to locate a 'Type' by the name: 'ProductStockItem'. Be sure to execute a query or call fetchMetadata first.
function createProductStockItem(initialValues) {
return this.manager.createEntity("ProductStockItem", initialValues);
}
When you rebuild your application, the metadata will get updated. No extra job needed for making the
metadata to get fetched with it's updated state.
Whenever you issue a query on an entity that is included inside the metadata, the updated metadata
will get fetched.
For creating an entity, if you navigate directly to the page of creating an entity prior to any page that includes a query, the metadata won't get fetched in this case.
When you called fetchMetadata(), you still get the error:
Unable to locate a 'Type' by the name: 'New Class'. Be sure to execute a query or call `fetchMetadata` first
That message doesn't indicate that the metadata already was fetched. It still tells you that the entity is unknown and the metadata still not fetched.
Why? Because createEntity() was called before fetchMetadata(). (you can set a break-point and see that in action)
I ran into this before, and what I did, I simply put the fetchMetadata() on application launch.
That will guarantee that it will get fetched first before any call to creating an entity.
Or you can just use a promise:
manager.fetchMetadata().then(createProductStockItem("Initial values"));