MVC 4 EF5 Database First set Default Values in Partial Class - asp.net-mvc-4

I'm new to MVC and trying to figure out how to set default values for partial classes. I have been searching for 2 days now, and can't get anything to work. Here is a supposed solution, but it doesn't work for me. I also tried the [DefaultValue(10)] data annotation.
Here is the auto generated partial class created from the edmx file
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace OTIS.Models.Admin
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class Company
{
public Company()
{
this.Facilities = new HashSet<Facility>();
}
public int CompanyID { get; set; }
[Required]
[Display(Name = "Company Name")]
public string CompanyName { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
public decimal ItemMargin { get; set; }
public decimal ServicesMargin { get; set; }
public decimal InvoiceTimeIncrement { get; set; }
public decimal CashDiscountPct { get; set; }
public decimal BaseServiceHourlyRate { get; set; }
public decimal HourlyPremiumRush { get; set; }
public decimal HourlyPremiumLate { get; set; }
public decimal HourlyPremiumCustomerMaterial { get; set; }
public int CreatedByID { get; set; }
public System.DateTime CreatedOn { get; set; }
public int ModifiedBy { get; set; }
public System.DateTime ModifiedOn { get; set; }
public virtual UserProfile UserProfile { get; set; }
public virtual UserProfile UserProfile1 { get; set; }
public virtual ICollection<Facility> Facilities { get; set; }
}
}
Here is my partial class I created to add annotations.
namespace OTIS.Models.Admin
{
[MetadataType(typeof(CompanyMD))]
public partial class Company
{
//public Company()
//{
// //private System.DateTime _currentDateTime = DateTime.Now;
// ////Set Default Values
// //CreatedByID = (int)Membership.GetUser().ProviderUserKey;
// //CreatedOn = _currentDateTime;
// //ModifiedBy = (int)Membership.GetUser().ProviderUserKey;
// //ModifiedOn = _currentDateTime;
//}
public string FullAddress
{
get
{
return this.City + ", " + this.State + " " + this.PostalCode;
}
}
public class CompanyMD
{
private System.DateTime _currentDateTime = DateTime.Now;
private int _currentUser = (int)Membership.GetUser().ProviderUserKey;
[Display(Name = "Company ID")]
public int CompanyID { get; set; }
[Required]
[Display(Name = "Company Name")]
public string CompanyName { get; set; }
[Display(Name = "Address")]
public string Address1 { get; set; }
[Display(Name = "Address 2")]
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
[Display(Name = "Zip")]
public string PostalCode { get; set; }
[Display(Name = "Address")]
public string FullAddress { get; set; }
[Display(Name = "Material Margin")]
public decimal ItemMargin { get; set; }
[Display(Name = "Overtime Margin")]
public decimal ServicesMargin { get; set; }
[Display(Name = "Invoice Hour Increment")]
public decimal InvoiceTimeIncrement { get; set; }
private decimal _cashDiscountPct;
[Display(Name = "Cash Discount %")]
[DisplayFormat(DataFormatString = "{0:P2}")]
public decimal CashDiscountPct
{
get { return _cashDiscountPct; }
set { _cashDiscountPct = value/100; }
}
[Display(Name = "Base Hourly Rate ($/Hr)")]
[DataType(DataType.Currency), DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = true)]
public decimal BaseServiceHourlyRate { get; set; }
[Display(Name = "Rush Premium ($/Hr)")]
[DataType(DataType.Currency), DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = true)]
public decimal HourlyPremiumRush { get; set; }
[Display(Name = "Late Premium ($/Hr)")]
[DataType(DataType.Currency), DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = true)]
[DefaultValue(75)]
public decimal HourlyPremiumLate { get; set; }
[Display(Name = "Cust Material Premium ($/Hr)")]
[DataType(DataType.Currency), DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = true)]
public decimal HourlyPremiumCustomerMaterial { get; set; }
[Display(Name = "Created By")]
public int CreatedByID { get; set; }
//{
// get { return _currentUser; }
// set { _currentUser = value; }
//}
[Display(Name = "Created On")]
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
//[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public System.DateTime CreatedOn
{
get { return _currentDateTime; }
set { _currentDateTime = value; }
}
[Display(Name = "Modified By")]
public int ModifiedBy { get; set; }
//{
// get { return _currentUser; }
// set { _currentUser = value; }
//}
[Display(Name = "Modified On")]
public System.DateTime ModifiedOn
{
get { return _currentDateTime; }
set { _currentDateTime = value; }
}
}
}
}
And then in my controller, I instantiate a new instance of the class to initialize it, but the values I set don't get set.
//
// GET: /Company/Create
public ActionResult Create()
{
ViewBag.CreatedByID = new SelectList(db.UserProfiles, "UserId", "UserName");
ViewBag.ModifiedBy = new SelectList(db.UserProfiles, "UserId", "UserName");
Company newCompany = new Company();
return View(newCompany);
}

Sorry this is so late, but I just solved a similar scenario myself.
I think the problem is how you refer to the partial class. It should be an empty reference to the partial class with no code. EF uses this "declaration" to link your partial class to your metadata class. So, your metadata class should look like this:
namespace OTIS.Models.Admin
{
[MetadataType(typeof(CompanyMD))]
public partial class Company
{} // <-- note the close bracket!
public class CompanyMD
{
private System.DateTime _currentDateTime = DateTime.Now;
private int _currentUser = (int)Membership.GetUser().ProviderUserKey;
public string FullAddress
{
get
{
return this.City + ", " + this.State + " " + this.PostalCode;
}
}
[Display(Name = "Company ID")]
public int CompanyID { get; set; }
[Required]
[Display(Name = "Company Name")]
public string CompanyName { get; set; }
// ....etc.... removed for brevity
} // close metadata class
} // close namespace
Hope this helps!

I found I needed to handle this in my Repository Class in a GetNew() method that would populate the default values of a new instance of the class.

Related

Calculate sum of decimal values from child class and display in parent class in one to many relationships in asp.net core web api

I am still new to asp.net core web api one to many relationships, I have two tables: Loan and loanHistories
Loan Model
public class Loan
{
[Key]
public int LoanID { get; set; }
[DataType(DataType.Currency)]
[Column(TypeName = "money")]
public decimal LoanAmount { get; set; }
[DataType(DataType.Currency)]
[Column(TypeName = "money")]
[Display(Name = "Loan Balance")]
private decimal _LoanBalance;
public decimal LoanBalance
{
get
{
return LoanAmount *interestRate;
}
set { _LoanBalance = value; }
}
[Display(Name = "Interest Rate")]
public decimal interestRate { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(Name = "Application Date")]
public DateTime ApplicationDate { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(Name = "Disbursement Date")]
public DateTime DisbursmentDate { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(Name = "Due Date")]
public DateTime DueDate { get; set; }
[Display(Name = "Defaulted")]
public bool Defaulted { get; set; }
[Display(Name = "Approved")]
public bool Approved { get; set; }
//Navigation property
public int CustomerID { get; set; }
public Customer customer { get; set; }
//public ICollection<LoanComments> loancomments { get; set; }
public ICollection<LoansHistories> loansHistories { get; set; }
}
LoanHistories model:
public class LoansHistories
{
[Key]
public int HistID { get; set; }
[DataType(DataType.Currency)]
[Column(TypeName = "money")]
[Display(Name = "Repaid Amount")]
public decimal RePaidIn { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(Name = "Repayement Date")]
public DateTime RepayementDateDate { get; set; }
[Display(Name = "No of paying interest only")]
public int NoOfPayinyingIntrestOnly { get; set; }
//Navigation properties
public int LoanID { get; set; }
public Loan loan { get; set; }
}
It generates the following Json data
[{"loanID":1,"loanAmount":1000.0000,"loanBalance":15000.000000,"interestRate":15.00,"applicationDate":"2022-03-28T00:00:00","disbursmentDate":"2022-03-28T00:00:00","dueDate":"2022-04-28T00:00:00","defaulted":false,"approved":true,"customerID":30290122,"customer":null,"loansHistories":[{"histID":1,"rePaidIn":500.0000,"repayementDateDate":"2022-03-28T00:00:00","noOfPayinyingIntrestOnly":1,"loanID":1},{"histID":4,"rePaidIn":2000.0000,"repayementDateDate":"2022-03-21T00:00:00","noOfPayinyingIntrestOnly":1,"loanID":1},{"histID":5,"rePaidIn":50000.0000,"repayementDateDate":"2022-03-28T00:00:00","noOfPayinyingIntrestOnly":1,"loanID":1},{"histID":6,"rePaidIn":50000.0000,"repayementDateDate":"2022-03-28T00:00:00","noOfPayinyingIntrestOnly":5,"loanID":1},{"histID":7,"rePaidIn":50000.0000,"repayementDateDate":"2022-03-28T00:00:00","noOfPayinyingIntrestOnly":1,"loanID":1},{"histID":8,"rePaidIn":50000.0000,"repayementDateDate":"2022-03-28T00:00:00","noOfPayinyingIntrestOnly":1,"loanID":1},{"histID":10,"rePaidIn":200.0000,"repayementDateDate":"2022-03-28T00:00:00","noOfPayinyingIntrestOnly":8,"loanID":1}]},{"loanID":2,"loanAmount":3000.0000,"loanBalance":45000.000000,"interestRate":15.00,"applicationDate":"2022-03-28T00:00:00","disbursmentDate":"2022-03-28T00:00:00","dueDate":"2022-03-28T00:00:00","defaulted":false,"approved":true,"customerID":30290122,"customer":null,"loansHistories":[{"histID":2,"rePaidIn":2000.0000,"repayementDateDate":"2022-03-08T00:00:00","noOfPayinyingIntrestOnly":1,"loanID":2},{"histID":9,"rePaidIn":50000.0000,"repayementDateDate":"2022-03-28T00:00:00","noOfPayinyingIntrestOnly":2,"loanID":2}]},{"loanID":3,"loanAmount":1000.0000,"loanBalance":150.000000,"interestRate":0.15,"applicationDate":"2022-03-28T00:00:00","disbursmentDate":"2022-03-28T00:00:00","dueDate":"2022-03-28T00:00:00","defaulted":false,"approved":true,"customerID":30290122,"customer":null,"loansHistories":[]},{"loanID":4,"loanAmount":2000.0000,"loanBalance":2300.000000,"interestRate":1.15,"applicationDate":"2022-03-28T00:00:00","disbursmentDate":"2022-03-28T00:00:00","dueDate":"2022-03-28T00:00:00","defaulted":false,"approved":true,"customerID":30290122,"customer":null,"loansHistories":[{"histID":3,"rePaidIn":2000.0000,"repayementDateDate":"2022-03-28T00:00:00","noOfPayinyingIntrestOnly":1,"loanID":4},{"histID":11,"rePaidIn":2000.0000,"repayementDateDate":"2022-03-28T00:00:00","noOfPayinyingIntrestOnly":3,"loanID":4},{"histID":12,"rePaidIn":2000.0000,"repayementDateDate":"2022-03-28T00:00:00","noOfPayinyingIntrestOnly":6,"loanID":4},{"histID":13,"rePaidIn":2000.0000,"repayementDateDate":"2022-03-28T00:00:00","noOfPayinyingIntrestOnly":6,"loanID":4},{"histID":14,"rePaidIn":2000.0000,"repayementDateDate":"2022-02-27T00:00:00","noOfPayinyingIntrestOnly":7,"loanID":4},{"histID":15,"rePaidIn":2000.0000,"repayementDateDate":"2022-03-28T00:00:00","noOfPayinyingIntrestOnly":1,"loanID":4},{"histID":16,"rePaidIn":2000.0000,"repayementDateDate":"2022-03-14T00:00:00","noOfPayinyingIntrestOnly":6,"loanID":4},{"histID":17,"rePaidIn":2000.0000,"repayementDateDate":"2022-03-28T00:00:00","noOfPayinyingIntrestOnly":3,"loanID":4},{"histID":18,"rePaidIn":2000.0000,"repayementDateDate":"2022-03-22T00:00:00","noOfPayinyingIntrestOnly":8,"loanID":4}]},{"loanID":5,"loanAmount":1000.0000,"loanBalance":1150.000000,"interestRate":1.15,"applicationDate":"2022-03-28T00:00:00","disbursmentDate":"2022-03-29T00:00:00","dueDate":"2021-04-29T00:00:00","defaulted":false,"approved":true,"customerID":30290122,"customer":null,"loansHistories":[]},{"loanID":8,"loanAmount":3000.0000,"loanBalance":3450.000000,"interestRate":1.15,"applicationDate":"2022-04-25T00:00:00","disbursmentDate":"2022-03-28T00:00:00","dueDate":"2022-04-26T00:00:00","defaulted":false,"approved":true,"customerID":30290122,"customer":null,"loansHistories":[]},{"loanID":9,"loanAmount":1000.0000,"loanBalance":1150.000000,"interestRate":1.15,"applicationDate":"2022-04-13T00:00:00","disbursmentDate":"2022-04-04T00:00:00","dueDate":"2022-04-25T00:00:00","defaulted":false,"approved":true,"customerID":30290122,"customer":null,"loansHistories":[]},{"loanID":10,"loanAmount":3000.0000,"loanBalance":3450.000000,"interestRate":1.15,"applicationDate":"2022-04-19T00:00:00","disbursmentDate":"2022-04-26T00:00:00","dueDate":"2022-04-25T00:00:00","defaulted":false,"approved":true,"customerID":40140676,"customer":null,"loansHistories":[{"histID":1012,"rePaidIn":300.0000,"repayementDateDate":"2022-04-05T00:00:00","noOfPayinyingIntrestOnly":1,"loanID":10},{"histID":1013,"rePaidIn":150.0000,"repayementDateDate":"2022-04-19T00:00:00","noOfPayinyingIntrestOnly":2,"loanID":10},{"histID":1014,"rePaidIn":300.0000,"repayementDateDate":"2022-04-11T00:00:00","noOfPayinyingIntrestOnly":3,"loanID":10},{"histID":1015,"rePaidIn":150.0000,"repayementDateDate":"2022-04-11T00:00:00","noOfPayinyingIntrestOnly":4,"loanID":10},{"histID":1016,"rePaidIn":300.0000,"repayementDateDate":"2022-04-06T00:00:00","noOfPayinyingIntrestOnly":5,"loanID":10},{"histID":1017,"rePaidIn":150.0000,"repayementDateDate":"2022-04-04T00:00:00","noOfPayinyingIntrestOnly":6,"loanID":10},{"histID":1018,"rePaidIn":300.0000,"repayementDateDate":"2022-04-05T00:00:00","noOfPayinyingIntrestOnly":7,"loanID":10},{"histID":1019,"rePaidIn":150.0000,"repayementDateDate":"2022-04-19T00:00:00","noOfPayinyingIntrestOnly":8,"loanID":10},{"histID":1020,"rePaidIn":150.0000,"repayementDateDate":"2022-04-02T00:00:00","noOfPayinyingIntrestOnly":9,"loanID":10},{"histID":1021,"rePaidIn":150.0000,"repayementDateDate":"2022-04-04T00:00:00","noOfPayinyingIntrestOnly":10,"loanID":10},{"histID":1022,"rePaidIn":100.0000,"repayementDateDate":"2022-04-06T00:00:00","noOfPayinyingIntrestOnly":12,"loanID":10},{"histID":1023,"rePaidIn":350.0000,"repayementDateDate":"2022-04-04T00:00:00","noOfPayinyingIntrestOnly":13,"loanID":10},{"histID":1024,"rePaidIn":100.0000,"repayementDateDate":"2022-04-12T00:00:00","noOfPayinyingIntrestOnly":14,"loanID":10},{"histID":1025,"rePaidIn":350.0000,"repayementDateDate":"2022-04-11T00:00:00","noOfPayinyingIntrestOnly":6,"loanID":10},{"histID":1026,"rePaidIn":100.0000,"repayementDateDate":"2022-04-20T00:00:00","noOfPayinyingIntrestOnly":14,"loanID":10},{"histID":1027,"rePaidIn":1000.0000,"repayementDateDate":"2022-04-12T00:00:00","noOfPayinyingIntrestOnly":16,"loanID":10},{"histID":1028,"rePaidIn":1000.0000,"repayementDateDate":"2022-04-04T00:00:00","noOfPayinyingIntrestOnly":17,"loanID":10},{"histID":1029,"rePaidIn":1000.0000,"repayementDateDate":"2022-04-04T00:00:00","noOfPayinyingIntrestOnly":18,"loanID":10}]},{"loanID":11,"loanAmount":1000.0000,"loanBalance":1150.000000,"interestRate":1.15,"applicationDate":"2022-04-26T00:00:00","disbursmentDate":"2022-04-25T00:00:00","dueDate":"2022-04-05T00:00:00","defaulted":false,"approved":true,"customerID":30290122,"customer":null,"loansHistories":[{"histID":1030,"rePaidIn":150.0000,"repayementDateDate":"2022-04-05T00:00:00","noOfPayinyingIntrestOnly":1,"loanID":11},{"histID":1031,"rePaidIn":150.0000,"repayementDateDate":"2022-04-12T00:00:00","noOfPayinyingIntrestOnly":5,"loanID":11}]},{"loanID":12,"loanAmount":1000.0000,"loanBalance":1150.000000,"interestRate":1.15,"applicationDate":"2022-04-24T00:00:00","disbursmentDate":"2022-04-24T00:00:00","dueDate":"2022-04-25T00:00:00","defaulted":false,"approved":true,"customerID":40140676,"customer":null,"loansHistories":[{"histID":1032,"rePaidIn":150.0000,"repayementDateDate":"2022-04-04T00:00:00","noOfPayinyingIntrestOnly":1,"loanID":12},{"histID":1033,"rePaidIn":150.0000,"repayementDateDate":"2022-03-28T00:00:00","noOfPayinyingIntrestOnly":3,"loanID":12}]},{"loanID":13,"loanAmount":2000.0000,"loanBalance":2300.000000,"interestRate":1.15,"applicationDate":"2022-04-24T00:00:00","disbursmentDate":"2022-04-25T00:00:00","dueDate":"2022-05-03T00:00:00","defaulted":false,"approved":true,"customerID":30290122,"customer":null,"loansHistories":[{"histID":1034,"rePaidIn":300.0000,"repayementDateDate":"2022-03-28T00:00:00","noOfPayinyingIntrestOnly":1,"loanID":13},{"histID":1035,"rePaidIn":300.0000,"repayementDateDate":"2022-04-12T00:00:00","noOfPayinyingIntrestOnly":9,"loanID":13}]},{"loanID":14,"loanAmount":1000.0000,"loanBalance":1150.000000,"interestRate":1.15,"applicationDate":"2022-04-25T00:00:00","disbursmentDate":"2022-04-06T00:00:00","dueDate":"2022-04-26T00:00:00","defaulted":false,"approved":true,"customerID":30290122,"customer":null,"loansHistories":[{"histID":1036,"rePaidIn":150.0000,"repayementDateDate":"2022-04-05T00:00:00","noOfPayinyingIntrestOnly":1,"loanID":14},{"histID":1037,"rePaidIn":1000.0000,"repayementDateDate":"2022-04-04T00:00:00","noOfPayinyingIntrestOnly":4,"loanID":14},{"histID":1038,"rePaidIn":150.0000,"repayementDateDate":"2022-04-18T00:00:00","noOfPayinyingIntrestOnly":4,"loanID":14},{"histID":1039,"rePaidIn":1000.0000,"repayementDateDate":"2022-04-11T00:00:00","noOfPayinyingIntrestOnly":5,"loanID":14},{"histID":1040,"rePaidIn":100.0000,"repayementDateDate":"2022-04-19T00:00:00","noOfPayinyingIntrestOnly":6,"loanID":14},{"histID":1041,"rePaidIn":50.0000,"repayementDateDate":"2022-04-04T00:00:00","noOfPayinyingIntrestOnly":7,"loanID":14},{"histID":1042,"rePaidIn":50.0000,"repayementDateDate":"2022-04-05T00:00:00","noOfPayinyingIntrestOnly":8,"loanID":14},{"histID":1043,"rePaidIn":50.0000,"repayementDateDate":"2022-04-06T00:00:00","noOfPayinyingIntrestOnly":8,"loanID":14},{"histID":1044,"rePaidIn":1000.0000,"repayementDateDate":"2022-03-28T00:00:00","noOfPayinyingIntrestOnly":89,"loanID":14}]},{"loanID":1014,"loanAmount":5000.0000,"loanBalance":5750.000000,"interestRate":1.15,"applicationDate":"2022-03-28T00:00:00","disbursmentDate":"2022-04-11T00:00:00","dueDate":"2022-04-12T00:00:00","defaulted":false,"approved":true,"customerID":40140676,"customer":null,"loansHistories":[{"histID":2035,"rePaidIn":750.0000,"repayementDateDate":"2022-04-11T00:00:00","noOfPayinyingIntrestOnly":1,"loanID":1014},{"histID":2036,"rePaidIn":1000.0000,"repayementDateDate":"2022-04-12T00:00:00","noOfPayinyingIntrestOnly":2,"loanID":1014},{"histID":2037,"rePaidIn":750.0000,"repayementDateDate":"2022-03-30T00:00:00","noOfPayinyingIntrestOnly":3,"loanID":1014}]}]
Now I want to calculate the total sum of rePaidIn within loanHistories table and display in loan table Has TotalRepaidIn with heading [NotMapped]: I have tried from the following link .it seems close to answer my question but it does not
Here is my Controller
[HttpGet]
public async Task<ActionResult<IEnumerable<Loan>>> Getloans()
{
return await _context.loans.Include(lh => lh.loansHistories).ToListAsync();
}
Any solution will be highly appreciated. Thanks in advance
Here is a whole working demo:
Model:
public class Loan
{
[Key]
public int LoanID { get; set; }
[DataType(DataType.Currency)]
[Column(TypeName = "money")]
public decimal LoanAmount { get; set; }
[DataType(DataType.Currency)]
[Column(TypeName = "money")]
[Display(Name = "Loan Balance")]
private decimal _LoanBalance;
[Column(TypeName = "decimal(18,2)")]
public decimal LoanBalance
{
get
{
return LoanAmount * interestRate;
}
set { _LoanBalance = value; }
}
[Column(TypeName = "decimal(18,2)")]
[Display(Name = "Interest Rate")]
public decimal interestRate { get; set; }
//....
[Display(Name = "Approved")]
public bool Approved { get; set; }
//public ICollection<LoanComments> loancomments { get; set; }
public ICollection<LoansHistories> loansHistories { get; set; }
[NotMapped]
public decimal TotalRepaidIn { get; set; } //add this...
}
public class LoansHistories
{
[Key]
public int HistID { get; set; }
[DataType(DataType.Currency)]
[Column(TypeName = "money")]
[Display(Name = "Repaid Amount")]
public decimal RePaidIn { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(Name = "Repayement Date")]
public DateTime RepayementDateDate { get; set; }
[Display(Name = "No of paying interest only")]
public int NoOfPayinyingIntrestOnly { get; set; }
public int LoanID { get; set; }
public Loan loan { get; set; }
}
Controller:
public async Task<ActionResult<IEnumerable<Loan>>> Getloans()
{
var data = await _context.loans.Include(lh => lh.loansHistories).Select(l=>new Loan()
{
TotalRepaidIn = l.loansHistories.Select(lh=>lh.RePaidIn).Sum(),
loansHistories = l.loansHistories,
ApplicationDate = l.ApplicationDate,
Defaulted=l.Defaulted,
DisbursmentDate= l.DisbursmentDate,
DueDate= l.DueDate,
LoanID=l.LoanID,
Approved=l.Approved,
interestRate=l.interestRate,
LoanAmount=l.LoanAmount
}).ToListAsync();
return data;
}
Update:
A better way is to change your model like below:
using System.Linq; //import this namespace...
public class Loan
{
[Key]
public int LoanID { get; set; }
[DataType(DataType.Currency)]
[Column(TypeName = "money")]
public decimal LoanAmount { get; set; }
private decimal _TotalRepaidIn;
[NotMapped]
public decimal TotalRepaidIn
{
get { return loansHistories.Sum(sum => sum.RePaidIn); }
set { _TotalRepaidIn = value; }
}
//other properties
public ICollection<LoansHistories> loansHistories { get; set; } = new List<LoansHistories>();
}
Controller:
public async Task<ActionResult<IEnumerable<Loan>>> Getloans()
{
return await _context.loans.Include(lh => lh.loansHistories).ToListAsync();
}

Save data on local storage

I am developing an app using Xamarin Forms PCL.
I want to save this class (I use this class as List in code)
public class TagInformation {
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string name { get; set; }
public bool isJob { get; set; }
public string _color { get; set; }
[Ignore]
public Color color { get; set; }
[Ignore]
public JobInformation jobInformation { get; set; }
public TagInformation(Color c, string n) {
color = c;
_color = c.ToHex();
name = n;
isJob = false;
}
public TagInformation() {
}
public void setColor() {
color = Color.FromHex(_color);
}
}
public class JobInformation {
public string shopName { get; set; }
public int wage { get; set; }
public bool isHoliday { get; set; }
public int holidayWage { get; set; }
public bool isMid { get; set; }
public int midnightWage { get; set; }
public bool[] holidayFlgs { get; set; }
public DateTime midStart { get; set; }
public DateTime midEnd { get; set; }
public int tranceportCost { get; set; }
public int closeDay { get; set; }
public int payMentDay { get; set; }
public TimeSpan shortRest { get; set; }
public TimeSpan longRest { get; set; }
public TimeSpan shortRestTime { get; set; }
public TimeSpan longRestTime { get; set; }
public TimeSpan commuteTime { get; set; }
public JobInformation() {
/* do samething */
}
}
Using SQLite, this class has another class, so it doesn't work on.
Is there any other way?
Do you have any ideas?
You could try to use Xamarin.Essentials: Preferences to save it as a json string.
1.Install the Newtonsoft.Json nuget.
2.Serialize your class to json string and save it with a key.
TagInformation tarinformation = xxxxx;
string jsonString = JsonConvert.SerializeObject(tarinformation);
Preferences.Set("your_key", jsonString); //save the data
3.Retrieve a value from preferences and deserialize the string.
var myValue = Preferences.Get("my_key", "default_value");//get the data string
TagInformation infor = JsonConvert.DeserializeObject<TagInformation>(myValue); //deserialize to your class

How to convert the object property type integer to string in .net core controller?

CMJobProgController.cs
This is the controlelr class
public IActionResult GetAll()
{
var allObj = _unitOfWork.cmJobProg.GetALL(j => j.AssignFrom == "JENNYCMS" || j.AssignTo=="JENNYCMS");
var pubcode = _unitOfWork.pubcode.GetALL(s => s.CodeType == "JPA" || s.CodeType=="DIV" );
foreach (CMJobProg c in allObj)
{
if (c.Division!=null)
{
foreach(PubCode p in pubcode)
{
if (c.Division == p.Code1 && p.CodeType=="DIV") //this part no problem cause the type is same
{
c.Division = p.CodeDesc;
}
}
}
if (c.JobAction != null)
{
foreach (PubCode p in pubcode)
{
if (c.JobAction.Tostring() == p.Code1 && p.CodeType == "JPA")
{
c.JobAction = p.CodeDesc; // this part will has error, cause my c.JobAction is integer and p.Code1 is string.
}
}
}
}
return Json(new { data = allObj });
}
CMJobProg.cs
This is the CMJobProg model class
public class CMJobProg
{
[Required]
[MaxLength(8)]
[Display(Name = "Job Number")]
[Column("JOB_NUMBER")]
[JsonPropertyName("jobnumber")]
public string JobNumber { get; set; }
[Display(Name = "Assign From")]
[MaxLength(22)]
[Column("ASSIGN_FROM")]
[JsonPropertyName("assignfrom")]
public string AssignFrom { get; set; }
[Display(Name = "Assign To")]
[MaxLength(22)]
[Column("ASSIGN_TO")]
[JsonPropertyName("assignto")]
public string AssignTo { get; set; }
[Column("DATE_ASSIGN")]
[JsonPropertyName("dateassign")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString ="{0:yyyy-MM-dd}", ApplyFormatInEditMode =true)]
public DateTime DateAssign { get; set; }
[Display(Name = "Job Action")]
[Range(0, 999)]
[Column("JOB_ACTION")]
[JsonPropertyName("jobaction")]
public int? JobAction { get; set; }
[Display(Name = "Remarks")]
[MaxLength(500)]
[Column("REMARKS")]
[JsonPropertyName("remarks")]
public string Remarks { get; set; }
[Display(Name = "Job Type")]
[Required]
[MaxLength(2)]
[Column("TYPE")]
[JsonPropertyName("type")]
public string Type { get; set; }
[MaxLength(2)]
[Column("DIVISION")]
[JsonPropertyName("division")]
public string Division { get; set; }
}
PubCode.cs
This is the PubCode model class
public class PubCode
{
[MaxLength(3)]
[Display(Name = "Code Type")]
[Column("CODE_TYPE")]
public string CodeType { get; set; }
[MaxLength(3)]
[Display(Name = "Code 1")]
[Column("CODE_1")]
public string Code1 { get; set; }
[MaxLength(3)]
[Display(Name = "Code 2")]
[Column("CODE_2")]
public string Code2 { get; set; }
[MaxLength(3)]
[Display(Name = "Code 3")]
[Column("CODE_3")]
public string Code3 { get; set; }
[MaxLength(3)]
[Display(Name = "Code 4")]
[Column("CODE_4")]
public string Code4 { get; set; }
[MaxLength(15)]
[Display(Name = "Code ACR")]
[Column("CODE_ACR")]
public string CodeACR { get; set; }
[MaxLength(100)]
[Display(Name = "Code Description")]
[Column("CODE_DESC")]
public string CodeDesc { get; set; }
}
}
Anyone could help me please? How to change the object property type integer to string for above condition?
The above CMJobProg.cs and Pubcode.cs are the model class that the data will reteive from the database.

json string downloaded with mising values c# webclient

I'm conding a rent car asp.net mvc application and I have a strange problem.
I used the skyscanner api to get the available cars list but the json string downloaded is always missing the attribute cars or there is cars that exist and are available.
string datacar = "";
String ch = "http://partners.api.skyscanner.net/apiservices/carhire/liveprices/v2/UK/eur/fr/" + ids + "/" + ide + "/" + dstart + "T" + tstart + "/" + dend + "T" + tend + "/30?apiKey=dh219253907683824017371755201462&userip=127.0.0.1";
Uri url = new Uri(ch);
// Uri url2 = new Uri("http://partners.api.skyscanner.net/apiservices/carhire/liveprices/v2/UK/eur/fr/27539733/27539733/2016-09-10T17:45/2016-09-17T17:45/30?apiKey=dh219253907683824017371755201462&userip=127.0.0.1");
CarModel model = new CarModel();
// for (int i = 0; i <= 20; i++)
// {
using (WebClient wc = new WebClient())
{
wc.Headers.Set("Content-Type", "application/json");
datacar = wc.DownloadString(url);
//datacar = wc.DownloadString(url2);
model = JsonConvert.DeserializeObject<CarModel>(datacar);
}
and here it is the carModel defintion
namespace carrent.Models
{
public class SubmittedQuery
{
public string market { get; set; }
public string currency { get; set; }
public string locale { get; set; }
public string pickup_place { get; set; }
public string dropoff_place { get; set; }
public string pickup_date_time { get; set; }
public string drop_off_date_time { get; set; }
public string driver_age { get; set; }
}
public class Image
{
public int id { get; set; }
public string url { get; set; }
}
public class CarClass
{
public int id { get; set; }
public int sort_order { get; set; }
public string name { get; set; }
}
public class DebugItem
{
public string type { get; set; }
public string title { get; set; }
public string content { get; set; }
}
public class CarModel
{
public SubmittedQuery submitted_query { get; set; }
public List<object> cars { get; set; }
public List<object> websites { get; set; }
public List<Image> images { get; set; }
public List<CarClass> car_classes { get; set; }
public List<DebugItem> debug_items { get; set; }
}
}
Ps: the strange thing in this problem is when I initialize an url (the url2) the code run perfectly
please guys help me to get the solution and thanks

WCF cannot implement interface - no matching return type

Why do I get this error:
Error 1 'JoomlaWebservice.KundeService' does not implement interface
member 'JoomlaWebservice.ServiceInterface.HentOpgave(int)'.
'JoomlaWebservice.KundeService.HentOpgave(int)' cannot implement
'JoomlaWebservice.ServiceInterface.HentOpgave(int)' because it does
not have the matching return type of
'JoomlaWebservice.Opgave'. C:\Visual Studio
2010\Projects\JoomlaWebservice\JoomlaWebservice\KundeService.svc.cs 12 18 JoomlaWebservice
Code (Service):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace JoomlaWebservice
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
public class KundeService : ServiceInterface
{
LIMSEntities LimsEntities;
public class OpgaveOverskrift
{
public int id { get; set; }
public string nummer { get; set; }
public string sagsnavn { get; set; }
public string sagsnr { get; set; }
public string matrix { get; set; }
public string status { get; set; }
}
public class Opgave
{
public int id { get; set; }
public string nummer { get; set; }
public string sagsnavn { get; set; }
public string sagsnr { get; set; }
public string journalnr { get; set; }
public string omnummer { get; set; }
public string matrix { get; set; }
public string status { get; set; }
public string anlaeg { get; set; }
public string anlaeg_kode2 { get; set; }
public bool akkrediteret { get; set; }
public string modtagdato { get; set; }
public string analysedato { get; set; }
public string rapportdato { get; set; }
public int antalproever { get; set; }
public string preopbevar { get; set; }
public int antalbilag { get; set; }
public string rapportnoter { get; set; }
public string afssagsbehandler_navn { get; set; }
public string afssagsbehandler_titel { get; set; }
public string hmansvarlig_navn { get; set; }
public string hmansvarlig_titel { get; set; }
public string kontakt { get; set; } //k0_kontakt01
public string afdeling { get; set; }
public string adresse { get; set; }
public string nation { get; set; }
public string postnummer { get; set; }
public string distrikt { get; set; }
public string postdist { get; set; } //std00002
}
public class Parameter
{
public int id { get; set; }
public int o1id { get; set; }
public string minimum { get; set; }
public string vejledende { get; set; }
public string maksimum { get; set; }
public string bemaerkning { get; set; }
public string parameter { get; set; }
public int metoderf { get; set; }
public int raekkefoelge { get; set; }
public string enhed { get; set; }
public string metoderef { get; set; }
public string detektionsgraense { get; set; }
public string nedremaalegraense { get; set; }
public string oevremaalegraense { get; set; }
public string knaek { get; set; }
public string nedreusikkerhedabs { get; set; }
public string nedreusikkerhedrel { get; set; }
public string oevreusikkerhedabs { get; set; }
public string oevreusikkerhedrel { get; set; }
public string resultat { get; set; }
public int a0id { get; set; }
public bool akkrediteret { get; set; }
public string analysested { get; set; }
public string kommentar { get; set; }
public int laboratorieid { get; set; } //a_internmetode
public string danakkode { get; set; } //k0_kontakt01
}
public List<Parameter> Parametre(int o1id)
{
using (LimsEntities = new LIMSEntities())
{
return (from i in LimsEntities.O2_Parameter01
where i.O1ID == o1id
select new Parameter()
{
a0id = i.A0ID.HasValue ? (int)i.A0ID : 0,
akkrediteret = i.Akkrediteret.HasValue ? (bool)i.Akkrediteret : false,
analysested = i.AnalyseSted,
bemaerkning = i.Bemærkning,
detektionsgraense = i.Detektionsgrænse,
enhed = i.Enhed,
id = i.ID,
knaek = i.Knæk,
kommentar = i.Kommentar,
maksimum = i.Maksimum,
metoderef = i.Metoderef,
metoderf = i.MetodeRf.HasValue ? (int)i.MetodeRf : 1,
minimum = i.Minimum,
nedremaalegraense = i.NedreMålegrænse,
nedreusikkerhedabs = i.NedreUsikkerhedAbs,
nedreusikkerhedrel = i.NedreUsikkerhedRel,
o1id = i.O1ID,
oevremaalegraense = i.ØvreMålegrænse,
oevreusikkerhedabs = i.ØvreUsikkerhedAbs,
oevreusikkerhedrel = i.ØvreUsikkerhedRel,
parameter = i.Parameter,
raekkefoelge = i.Rækkefølge.HasValue ? (int)i.Rækkefølge : 1,
resultat = i.Resultat,
vejledende = i.VejledendeVærdi,
laboratorieid = i.ParameterIAnalyser.A_InternMetode.K0ID.HasValue ? (int)i.ParameterIAnalyser.A_InternMetode.K0ID : 0,
danakkode = i.ParameterIAnalyser.A_InternMetode.K0_Kontakt01.DANAKkode
}).ToList();
}
}
public class Proeve
{
public int id { get; set; }
public int o0id { get; set; }
public string omfang { get; set; }
public string formaal { get; set; }
public string proevetager { get; set; }
public string udtagdatostart { get; set; }
public string udtagdatoslut { get; set; }
public string dybde { get; set; }
public string proeveid { get; set; }
public string abtekst { get; set; } //ab_formål
}
public List<Proeve> Proever(int o0id)
{
using (LimsEntities = new LIMSEntities())
{
return (from i in LimsEntities.O1_Prøve
join f in LimsEntities.AB_Formål on i.Formål equals f.ID.ToString() into fs
from f in fs.DefaultIfEmpty()
where i.O0ID == o0id
select new Proeve()
{
id = i.ID,
o0id = i.O0ID,
omfang = i.Omfang,
formaal = i.Formål,
proevetager = i.Prøvetager,
udtagdatostart = i.UdtagDatoStart,
udtagdatoslut = i.UdtagDatoSlut,
dybde = i.Dybde,
proeveid = i.PrøveID,
abtekst = f == null ? "" : f.Tekst
}).ToList();
}
}
public int Login(String username, String password)
{
LimsEntities = new LIMSEntities();
IEnumerable<K1_Kontaktperson01> kontakter = from k in LimsEntities.K1_Kontaktperson01
where k.HSBrugernavn == username && k.HSAdgangskode == password
select k;
return kontakter.FirstOrDefault().K0ID;
}
public List<OpgaveOverskrift> OpgaveOverskrifter(int k0id)
{
using (LimsEntities = new LIMSEntities())
{
return (from i in LimsEntities.O0_Opgave01
where i.K0ID == k0id
select new OpgaveOverskrift()
{
id = i.ID,
nummer = i.Nummer,
sagsnavn = i.Sagsnavn,
sagsnr = i.SagsNr,
matrix = i.Matrix,
status = i.Status
}).ToList();
}
}
public Opgave HentOpgave(int o0id)
{
/* Opgave test = new Opgave();
return test;*/
using (LimsEntities = new LIMSEntities())
{
return (from i in LimsEntities.O0_Opgave01
where i.ID == o0id
select new Opgave()
{
id = i.ID,
nummer = i.Nummer,
sagsnavn = i.Sagsnavn,
sagsnr = i.SagsNr,
matrix = i.Matrix,
journalnr = i.JournalNr,
omnummer = i.OMNummer,
status = i.Status,
anlaeg = i.Anlæg,
anlaeg_kode2 = i.Anlæg_Kode2,
akkrediteret = i.Akkrediteret,
modtagdato = i.ModtagDato,
analysedato = i.AnalyseDato,
rapportdato = i.RapportDato,
antalproever = i.AntalPrøver.HasValue ? (int)i.AntalPrøver.Value : 0,
preopbevar = i.PreOpbevar,
antalbilag = i.AntalBilag.HasValue ? (int)i.AntalBilag.Value : 0,
rapportnoter = i.RapportNoter,
afssagsbehandler_navn = i.AFSSagsbehandler_Navn,
afssagsbehandler_titel = i.AFSSagsbehandler_Titel,
hmansvarlig_navn = i.HMAnsvarlig_Navn,
hmansvarlig_titel = i.HMAnsvarlig_Titel,
kontakt = i.K0_Kontakt01.Kontakt,
afdeling = i.K0_Kontakt01.Afdeling,
adresse = i.K0_Kontakt01.Adresse,
nation = i.K0_Kontakt01.Nation,
postnummer = i.K0_Kontakt01.Postnummer,
distrikt = i.K0_Kontakt01.Distrikt,
postdist = i.K0_Kontakt01.std00002.postdist
}).FirstOrDefault();
}
}
}
}
Code (Interface):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace JoomlaWebservice
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
[ServiceContract]
public interface ServiceInterface
{
[OperationContract]
int Login(String username, String password);
[OperationContract]
Opgave HentOpgave(int o0id);
// TODO: Add your service operations here
}
// Use a data contract as illustrated in the sample below to add composite types to service operations.
[DataContract]
public class OpgaveOverskrift
{
[DataMember]
public int id { get; set; }
[DataMember]
public string sagsnavn { get; set; }
[DataMember]
public string sagsnr { get; set; }
[DataMember]
public string matrix { get; set; }
[DataMember]
public string status { get; set; }
}
[DataContract]
public class Opgave
{
[DataMember]
public int id { get; set; }
[DataMember]
public string nummer { get; set; }
[DataMember]
public string sagsnavn { get; set; }
[DataMember]
public string sagsnr { get; set; }
[DataMember]
public string journalnr { get; set; }
[DataMember]
public string omnummer { get; set; }
[DataMember]
public string matrix { get; set; }
[DataMember]
public string status { get; set; }
[DataMember]
public string anlaeg { get; set; }
[DataMember]
public string anlaeg_kode2 { get; set; }
[DataMember]
public bool akkrediteret { get; set; }
[DataMember]
public string modtagdato { get; set; }
[DataMember]
public string analysedato { get; set; }
[DataMember]
public string rapportdato { get; set; }
[DataMember]
public int antalproever { get; set; }
[DataMember]
public string preopbevar { get; set; }
[DataMember]
public int antalbilag { get; set; }
[DataMember]
public string rapportnoter { get; set; }
[DataMember]
public string afssagsbehandler_navn { get; set; }
[DataMember]
public string afssagsbehandler_titel { get; set; }
[DataMember]
public string hmansvarlig_navn { get; set; }
[DataMember]
public string hmansvarlig_titel { get; set; }
[DataMember]
public string kontakt { get; set; } //k0_kontakt01
[DataMember]
public string afdeling { get; set; }
[DataMember]
public string adresse { get; set; }
[DataMember]
public string nation { get; set; }
[DataMember]
public string postnummer { get; set; }
[DataMember]
public string distrikt { get; set; }
[DataMember]
public string postdist { get; set; } //std00002
}
[DataContract]
public class Proeve
{
[DataMember]
public int id { get; set; }
[DataMember]
public int o0id { get; set; }
[DataMember]
public string omfang { get; set; }
[DataMember]
public string formaal { get; set; }
[DataMember]
public string proevetager { get; set; }
[DataMember]
public string udtagdatostart { get; set; }
[DataMember]
public string udtagdatoslut { get; set; }
[DataMember]
public string dybde { get; set; }
[DataMember]
public string proeveid { get; set; }
[DataMember]
public string abtekst { get; set; } //ab_formål
}
[DataContract]
public class Parameter
{
[DataMember]
public int id { get; set; }
[DataMember]
public int o1id { get; set; }
[DataMember]
public string minimum { get; set; }
[DataMember]
public string vejledende { get; set; }
[DataMember]
public string maksimum { get; set; }
[DataMember]
public string bemaerkning { get; set; }
[DataMember]
public string parameter { get; set; }
[DataMember]
public int metoderf { get; set; }
[DataMember]
public int raekkefoelge { get; set; }
[DataMember]
public string enhed { get; set; }
[DataMember]
public string metoderef { get; set; }
[DataMember]
public string detektionsgraense { get; set; }
[DataMember]
public string nedremaalegraense { get; set; }
[DataMember]
public string oevremaalegraense { get; set; }
[DataMember]
public string knaek { get; set; }
[DataMember]
public string nedreusikkerhedabs { get; set; }
[DataMember]
public string nedreusikkerhedrel { get; set; }
[DataMember]
public string oevreusikkerhedabs { get; set; }
[DataMember]
public string oevreusikkerhedrel { get; set; }
[DataMember]
public string resultat { get; set; }
[DataMember]
public int a0id { get; set; }
[DataMember]
public bool akkrediteret { get; set; }
[DataMember]
public string analysested { get; set; }
[DataMember]
public string kommentar { get; set; }
[DataMember]
public int laboratorieid { get; set; } //a_internmetode
[DataMember]
public string danakkode { get; set; } //k0_kontakt01
}
}
You're returning JoomlaWebservice.KundeService.Opgave, not JoomlaWebservice.Opgave. You need to change your code to either return the contract directly or to map between your created object and the contract.