I am working on an ASP.NET Web API project and I have a database that I am using, and the model that I am working on look something like this
public class PAY
{
public int ID { get; set; }
public string PAY_CODE { get; set; }
public Nullable<decimal> PAY_CASH { get; set; }
}
and I have a simple post method look like this:
[HttpPost]
public string AddPayROW(string PAY_CODE, decimal PAY_CASH,)
{
var PAY = new PAY()
{
PAY_CODE = PAY_CODE,
PAY_CASH = PAY_CASH,
};
db.PAY.Add(PAY);
db.SaveChanges();
return "Row added successfully";
}
My problem is kind of weird but when I post this decimal value to the table the last number is zero
For example, if I tried to post 1.999 will be saved like this 1.990
I am using SQL Server and the datatype is decimal(16, 3)
How can I fix this problem?
On your OnModelCreating function add this code,
modelBuilder.Entity<PAY>().Property(x => x.PAY_CASH).HasPrecision(18,3);
Hope it works.
Edit : Do you have DbContext like this? For example;
public partial class DBO : DbContext
{
public DBO()
: base("ConStrEtc")
{ }
public virtual DbSet<PAY> PAYs { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<PAY>().Property(x => x.PAY_CASH).HasPrecision(18, 3);
}
}
public class PAY
{
public int ID { get; set; }
public string PAY_CODE { get; set; }
public Nullable<decimal> PAY_CASH { get; set; }
}
Related
I'm using a EF DbSet<FiveMinStockHistory>. And now, I need a code snippet showing how to implement the EF6+ method DbContext.OnModelCreating(DbModelBuilder modelBuilder) to populate a code-first database. I could not find any good examples.
public class FiveMinStockHistory
{
public int Id { get; set; }
public Dictionary<string, string> Meta_Data { get; set; }
public Dictionary<string, TimeSeries> Lhocv { get; set; }
}
public class TimeSeries
{
public decimal Open { get; set; }
public decimal High { get; set; }
public decimal Low { get; set; }
public decimal Close { get; set; }
public double Volume { get; set; }
}
Thanks!!!
You can seed a database in many ways. Usually, you want it to have happened on startup. So you create a DbInitializer.cs class that has a static initialize method.
public static void Initialize(MyDbContext context)
{
context.Database.EnsureCreated();
// Create the objects you want to insert into DbContext.
// Write it to a variable, for example, "var ExampleData".
// Add example data.
context.FiveMinStockHistory.Add(ExampleData)
context.SaveChanges();
}
Then you could just run it on startup:
public void Configure(IApplicationBuilder app, MyDbContext context)
{
MyDatabaseInitializer.Initialize(context);
}
Easy peasy. Good luck!
I am trying to get data from a table with a get request with a controller. When I make the request with a normal table (TestTable) it is ok, but if I make the request with a relational table I get the fail message:
"The 'ObjectContent`1' type failed to serialize the response body for
content type 'application/xml; charset=utf-8'."
My controller (Mdata):
namespace ScThAsp.Controllers
{
public class MDataController : ApiController
{
public IEnumerable<Måledata> Get()
{
using (var e = new SCTHDBEntities())
{
return e.Måledata.ToList();
}
}
public TestTable Get(int id)
{
using (SCTHDBEntities entities = new SCTHDBEntities())
{
return entities.TestTable.FirstOrDefault(e => e.Id == 1);
}
}
}
}
My Table for måledata is:
public partial class Måledata
{
public int MDid { get; set; }
public Nullable<int> BBid { get; set; }
public Nullable<decimal> Måling1 { get; set; }
public Nullable<decimal> Måling2 { get; set; }
public Nullable<decimal> Måling3 { get; set; }
public Nullable<decimal> Måling4 { get; set; }
public Nullable<System.DateTime> RegTid { get; set; }
public virtual BuildBoard BuildBoard { get; set; }
}
My database looks like:
Database
See link..
I think I mayby should make a inner join with the other table connected to Måledata table - I am not sure how to do that in a EF environment.
I have really tried a lot now - hope for an answer. Thanks
Your class Måledata contains more data that you presented (it is marked as partial) and probably contains stuff related to EF. This magic stuff is not serializable. To avoid problem rewrite results to a plain object with properties you need. This object must be serializable (if contains plain properties and classes it will).
Building upon Piotr Stapp's answer you need to create a DTO (Data Transfer Object) for your Måledata which contains properties as your model, Måledata other than the EF properties. Use some sort of Mapper, maybe AutoMapper to map the required properties in your final response.
public class MaledataDTO
{
public int MDid { get; set; }
public int? BBid { get; set; }
public decimal? Måling1 { get; set; }
public decimal? Måling2 { get; set; }
public decimal? Måling3 { get; set; }
public decimal? Måling4 { get; set; }
public DateTime? RegTid { get; set; }
//... other properties
}
public IEnumerable<MaledataDTO> Get()
{
using (var e = new SCTHDBEntities())
{
var result = e.Måledata.ToList();
return Mapper.Map<List<MaledataDTO>>(result);
}
}
I found 2 solutions.
1) Solution was with Automapper (thanks Abdul). Installing automapper and a Using Automapper. Added a class called MåledataDTO : ` public class MåledataDTO
{
public int MDid { get; set; }
public int? BBid { get; set; }
public decimal? Måling1 { get; set; }
public decimal? Måling2 { get; set; }
public decimal? Måling3 { get; set; }
public decimal? Måling4 { get; set; }
public DateTime? RegTid { get; set; }
//... other properties
}
`
In my controller I used the following code
public IEnumerable<MåledataDTO> Get()
{
using (var e = new SCTHDBEntities())
{
Mapper.Initialize(config =>
{
config.CreateMap<Måledata, MåledataDTO>();
});
var result = e.Måledata.ToList();
return Mapper.Map<List<MåledataDTO>>(result);
2: In the second solution: In the picture you see the relations bewtween the tables - made in VS - but that creates a problem in the tables Get SET classes. The relation creates a Virtual object in the class - like mentioned before
public virtual BuildBoard BuildBoard { get; set; }
If you delete the relations and make the public partial class Måledata like
in this video
https://www.youtube.com/watch?v=4Ir4EIqxYXQ
the controller should then have one of two solutions:
using (SCTHDBEntities e = new SCTHDBEntities()) {
//this works
//var knud = new List<Måledata>();
//knud = (e.BuildBoard.Join(e.Måledata, c => c.BBid, o => o.BBid,
// (c, o) => o)).ToList();
//return knud;
//this works too
return (from p in e.BuildBoard
where p.BBid == 1
from r in e.Måledata
where r.BBid == p.BBid
select p).ToList();
That was that
Gorm
I have a model which is storing mycustomer new request information.
In another history model i am storing all previous request of the customer.
In view i would like to take new order and also see his previous orders and suggest some food after seeing his previous order.
Here are my models...
public class CustomerFoodModel
{
public DateTime FoodRequestCreated { get; set; }
public string FoodRequestType { get; set; }
...
...
}
public class CustomerHistoryModel
{
public string Name { get; set; }
public DateTime FoodRequestCreated { get; set; }
public string FoodRequestType { get; set; }
...
...
}
Helper.cs file
public static CustomerFoodModel getCustomerDetails(int id) // id is loyalty card number
{
// get details from (cutomer) sql table
//store it in (CustomerFoodModel)
// check if it has previous orders
getCustomerHistoryDetails(id);
....
}
public static CustomerHistoryModel getCustomerHistoryDetails(int id)
{
// get deails from (history) sql table
// store it in (CustomerHistoryModel
}
In my controller, I am passing my (CustomerFoodModel) to the view.
public ActionResult EditCustomerRequest(int id, string name, string date)
{
CustomerFoodModel CRequest = Helper.getCustomerDetails(id);
...
return PartialView("EditCustomerRequest",CRequest);
}
How do I show the (CustomerHistoryModel) in the same view.? Is there possible to include (CustomerHistoryModel) in (CustomerFoodModel)?
Create a new class to wrap both of the model.
public class CustomerFoodModel
{
public CustomerFoodModel CustomerFood { get; set; }
public CustomerHistoryModel CustomerHistory { get; set; }
}
And on your controller
public ActionResult EditCustomerRequest(int id, string name, string date)
{
CustomerFoodModel CRequest = Helper.getCustomerDetails(id);
CustomerHistoryModel CHModel = Helper. getCustomerHistoryDetails(id);
return PartialView("EditCustomerRequest",new CustomerFoodModel(){
CustomerFood = CRequest,
CustomerHistory = CHModel
});
}
I think the best approach is to use a partial view inside the main view. The partial view can call back to another controller to get a new model and pass that model to the partial view. This keeps things better seperated.
Look at this post for a similar issue.
Using partial views in ASP.net MVC 4
Use wrapper class which contain both of class
public class CustomerViewModel
{
public CustomerFoodModel FoodModel { get; set; }
public CustomerHistoryModel HistoryModel { get; set; }
}
You have a few options. I would probably could create a view model that contains both of your models:
public class CustomerViewModel
{
public CustomerFoodModel FoodModel { get; set; }
public CustomerHistoryModel HistoryModel { get; set; }
}
Or, depending on your data structure, you may have multiple history entries per customer:
public class CustomerViewModel
{
public CustomerFoodModel FoodModel { get; set; }
public List<CustomerHistoryModel> HistoryModels { get; set; }
}
Then your getCustomerDetails function would return a CustomerViewModel instead.
Maybe a simple question, but I can't seem to figure it out. Saving a collection to a model when adding a model to the database isn't working. I have a site which uses asp.net MVC and entity framework.
The models:
public class Event
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public ICollection<EventRange> Ranges { get; set; }
}
public class EventRange
{
public int Id { get; set; }
public string RangeName { get; set; }
public string RangeDescription { get; set; }
public int Capacitiy { get; set; }
}
The controller actions:
[HttpPost]
public ActionResult Create(Event model)
{
ICollection<EventRange> eventRanges = new Collection<EventRange>();
var range = new EventRange {RangeName = "testrange", RangeDescription = "test", Capacitiy = 5}
eventRanges.Add(range);
model.Ranges = eventRanges;
db.Events.Add(model);
db.SaveChanges();
return View();
}
public ActionResult Events()
{
return View(db.Events);
}
When setting a breakpoint in the Events action and evaluated the query, the Range isn't saved to the event:
Code Screenshot
Note that that the database created for the eventrange model by EF does save the range:
EF DB Screenshot
Am I doing something wrong?
What if you mark the Ranges property as virtual?
public virtual ICollection<EventRange> Ranges { get; set; }
This seems like an easy question but I can't seem to find the answer.
I have a Model that looks like this ...
public class Application
{
public int Id { get; set; }
public string Title { get; set; }
public string LeadProgrammer { get; set; }
public string ConnectionStringCode { get; set; }
}
public class ApplicationDBContext : DbContext
{
public DbSet<Application> Applications { get; set; }
}
My actual table name is DBA_APPLICATIONS ... the model is, of course, just looking for dbo.Applications. How can I change this routing to the actual table?
Add this in your ApplcationDBContext class.
public class ApplicationDBContext : DbContext
{
public DbSet<Application> Applications { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Application>().ToTable("DBA_APPLICATIONS");
// otherwise EF assumes the table is called "Applications"
}
}