I'm following some examples to learn asp.net core with Entity Framework, I'm having trouble saving a user's data, I have the class that was generated from an existing database (Database First), and created a ViewModel to work with the views, my class generated from the database came with some dependencies, "ICollection", I just need to update some fields of the table, when I try to save the error occurs below:
Microsoft.EntityFrameworkCore.DbUpdateException: 'An error occurred while updating the entries. See the inner exception for details.'
SqlException: String or binary data would be truncated.
The statement has been terminated.
My Model:
using System;
using System.Collections.Generic;
namespace PetAlerta.Domain.Entities
{
public partial class Petshop
{
public Petshop()
{
Agendabanhos = new HashSet<Agendabanhos>();
Agendaconsultas = new HashSet<Agendaconsultas>();
Agendavacinas = new HashSet<Agendavacinas>();
Banhos = new HashSet<Banhos>();
Chat = new HashSet<Chat>();
Configshop = new HashSet<Configshop>();
Consultas = new HashSet<Consultas>();
Pets = new HashSet<Pets>();
Shopdonos = new HashSet<Shopdonos>();
}
public int Cod { get; set; }
public string Razaosocial { get; set; }
public string Nomefant { get; set; }
public string Cnpj { get; set; }
public string Endereco { get; set; }
public string Cidade { get; set; }
public string Uf { get; set; }
public string Complemento { get; set; }
public string Bairro { get; set; }
public string Num { get; set; }
public string Cep { get; set; }
public string Endecomp { get; set; }
public string Email { get; set; }
public string Fone1 { get; set; }
public string Fone2 { get; set; }
public string Celular { get; set; }
public string Senha { get; set; }
public string Img { get; set; }
public string Nomeresp { get; set; }
public string Site { get; set; }
public string Seguimento { get; set; }
public DateTime? Dataacesso { get; set; }
public int Ativo { get; set; }
public ICollection<Agendabanhos> Agendabanhos { get; set; }
public ICollection<Agendaconsultas> Agendaconsultas { get; set; }
public ICollection<Agendavacinas> Agendavacinas { get; set; }
public ICollection<Banhos> Banhos { get; set; }
public ICollection<Chat> Chat { get; set; }
public ICollection<Configshop> Configshop { get; set; }
public ICollection<Consultas> Consultas { get; set; }
public ICollection<Pets> Pets { get; set; }
public ICollection<Shopdonos> Shopdonos { get; set; }
}
}
My ViewModel:
using System.ComponentModel.DataAnnotations;
namespace PetAlerta.MVC.ViewModels
{
public class PetShopViewModel
{
[Key]
public int Cod { get; set; }
public string Razaosocial { get; set; }
public string Nomefant { get; set; }
public string Cnpj { get; set; }
public string Endereco { get; set; }
public string Cidade { get; set; }
public string Uf { get; set; }
public string Complemento { get; set; }
public string Bairro { get; set; }
public string Num { get; set; }
public string Cep { get; set; }
public string Endecomp { get; set; }
public string Email { get; set; }
public string Fone1 { get; set; }
public string Fone2 { get; set; }
public string Celular { get; set; }
public string Nomeresp { get; set; }
public string Site { get; set; }
}
}
I'm using the automapper to map the Model to the ViewModel and the ViewlModel to the Model.
Controller:
[HttpPost]
public IActionResult SalvaPerfil([FromBody] PetShopViewModel petshopViewModel)
{
if (ModelState.IsValid)
{
var petshop = Mapper.Map<PetShopViewModel, Petshop>(petshopViewModel);
_PetApp.Update(petshop);
return Content("fim..."); //<<=== ERROR
}
return Content("ERRO");
}
I just want to update the fields that is in the ViewModel, other fields like password, image url etc ... I want to update separately at another time, where am I going wrong? how to do this?
Thanks!
Error is very clear. Just check the columns length and properties value, you'll find that the length of one or more fields is NOT big enough to hold the data you are trying to insert. For example, if one field is a varchar(8) length, and you try to add 10 characters in to it, you will get this error.
Related
I am trying to get the list of commiters
In beginning I ask GitHub API (v3) to get repositories:
https://api.github.com/users/{userName}/repos
ok, got some list, and I got there repository name, which I want to use to get all commits
https://api.github.com/repos/{userName}/{repoName}/commits
the address is correct, I get some information, but...
I don't know how to create classes, I don't understand this JSON structure
see the example on https://api.github.com/repos/octocat/Hello-World/git/commits/
its something like this:
[0]
{
"sha",
"commit":{
"commiter":{
"name",
"email",
}
}
}
so... the commit class should have commit...?
I have tried something like this:
the Commit class
[DataContract(Name="commits")]
public class Commit
{
[DataMember(Name="sha")]
public string Sha{get;set;}
[DataMember(Name="commiter")]
public Commiter Commiter{get;set;}
}
and the commiter class:
[DataContract(Name="commiter")]
public class Commiter
{
[DataMember(Name="name")]
public string Name{get;set;}
[DataMember(Name="email")]
public string Email {get;set;}
[DataMember(Name="date")]
public string Date{get;set;}
[DataMember(Name="message")]
public string Message{get;set;}
}
but the only result when I ask for commits is the SHA field from Commit class, the committer is always null
can someone help me :)?
For generate my POCO class I always use :
http://json2csharp.com/
It's automatic.
For your API it's :
public class Author
{
public string name { get; set; }
public string email { get; set; }
public DateTime date { get; set; }
}
public class Committer
{
public string name { get; set; }
public string email { get; set; }
public DateTime date { get; set; }
}
public class Tree
{
public string sha { get; set; }
public string url { get; set; }
}
public class Verification
{
public bool verified { get; set; }
public string reason { get; set; }
public string signature { get; set; }
public string payload { get; set; }
}
public class Commit
{
public Author author { get; set; }
public Committer committer { get; set; }
public string message { get; set; }
public Tree tree { get; set; }
public string url { get; set; }
public int comment_count { get; set; }
public Verification verification { get; set; }
}
public class Author2
{
public string login { get; set; }
public int id { get; set; }
public string node_id { get; set; }
public string avatar_url { get; set; }
public string gravatar_id { get; set; }
public string url { get; set; }
public string html_url { get; set; }
public string followers_url { get; set; }
public string following_url { get; set; }
public string gists_url { get; set; }
public string starred_url { get; set; }
public string subscriptions_url { get; set; }
public string organizations_url { get; set; }
public string repos_url { get; set; }
public string events_url { get; set; }
public string received_events_url { get; set; }
public string type { get; set; }
public bool site_admin { get; set; }
}
public class Committer2
{
public string login { get; set; }
public int id { get; set; }
public string node_id { get; set; }
public string avatar_url { get; set; }
public string gravatar_id { get; set; }
public string url { get; set; }
public string html_url { get; set; }
public string followers_url { get; set; }
public string following_url { get; set; }
public string gists_url { get; set; }
public string starred_url { get; set; }
public string subscriptions_url { get; set; }
public string organizations_url { get; set; }
public string repos_url { get; set; }
public string events_url { get; set; }
public string received_events_url { get; set; }
public string type { get; set; }
public bool site_admin { get; set; }
}
public class Parent
{
public string sha { get; set; }
public string url { get; set; }
public string html_url { get; set; }
}
public class RootObject
{
public string sha { get; set; }
public string node_id { get; set; }
public Commit commit { get; set; }
public string url { get; set; }
public string html_url { get; set; }
public string comments_url { get; set; }
public Author2 author { get; set; }
public Committer2 committer { get; set; }
public List<Parent> parents { get; set; }
}
i am getting Getting Object reference not set to an instance of an object error
my code and the image are attached below
public class Backlogitem
{
public string Name { get; set; }
public int ID { get; set; }
public string State { get; set; }
// public DateTime? due { get; set; }
public int priorty { get; set; }
public int Size { get; set; }
// public int effort { get; set; }
public int StoryPoints { get; set; }
public string DoneStatus { get; set; }
public string StoryOwner { get; set; }
public string Assignedto { get; set; }
public string StoryAuthor { get; set; }
public string IterationPath { get; set; }
}
workitemlist image
rest of the code is pasted here
https://github.com/akhiljain1611/TFS/blob/master/README.md
You need to initialize the lists (Issues, Tasks and PBacklog) before you can begin adding items to it. I have done it using a constructor:
public class WorkItemViewModel
{
public int Id { get; set; }
public string Title { get; set; }
public string AssignedTo { get; set; }
public string WorkitemType { get; set; }
public string Priorty { get; set; }
public string IterationPath { get; set; }
public string State { get; set; }
public List<TFSIssue> Issues { get; set; }
public List<TFSTask> Tasks { get; set; }
public List<Backlogitem> PBacklog { get; set;}
public WorkItemViewModel() // Added a public constructor
{
Issues = new List<TFSIssue>();
Tasks = new List<TFSTask>();
PBacklog = new List<Backlogitem>();
}
}
I have created an API that I am now attempting to access through another application. Even though I am using Newtonsoft.JSON to both serialize and deserialize the JSON, I am encountering a conversion error, with the following InnerException:
{"Could not cast or convert from System.String to System.Collections.Generic.List`1[MidamAPI.Models.ManagerDTO]."}
The following is the snippet that throws the error (in RESTFactory):
public List<T> Execute<T>(String endPoint) where T : new() {
RestClient client = new RestClient(BASE_URL);
IRestRequest req = new RestRequest(endPoint);
req.AddHeader("Authorization", "Bearer " + this._token);
var response = client.Execute(req).Content;
List<T> responseData = JsonConvert.DeserializeObject<List<T>>(response);
return responseData;
}
which is called here:
{
RegisterViewModel vm = new RegisterViewModel();
RESTFactory factory = new RESTFactory((String)Session["bearer"]);
vm.availableManager = factory.Execute<ManagerDTO>("managers");
vm.availableProperties = factory.Execute<PropertyDTO>("locations");
vm.availableTrainers = factory.Execute<TrainerDTO>("trainers");
return View(vm);
}
The information is coming from the following API controller action (in a separate application):
[LocalFilter]
[RoutePrefix("managers")]
public class ManagersController : ApiController
{
UnitOfWork worker = new UnitOfWork();
[Route("")]
public string Get()
{
IEnumerable<ManagerDTO> dtoList = Mapper.Map<List<Manager>, List<ManagerDTO>>(worker.ManagerRepo.Get().ToList());
foreach (ManagerDTO dto in dtoList)
{
Manager manager = worker.ManagerRepo.GetByID(dto.ID);
dto.Stores = (Mapper.Map<IEnumerable<Property>, IEnumerable<PropertyDTO>>(manager.Properties)).ToList();
}
return JsonConvert.SerializeObject(dtoList);
}
The DTOs are the same in both applications:
{
public class ManagerDTO
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public List<PropertyDTO> Stores { get; set; }
}
public class PropertyDTO
{
public int ID;
public string ShortName { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string Phone { get; set; }
public string Lat { get; set; }
public string Long { get; set; }
public string GooglePlaceID { get; set; }
public string PropertyNumber { get; set; }
public int ManagerID { get; set; }
public int TrainerID { get; set; }
public string ManagerName { get; set; }
public string ManagerEmail { get; set; }
public string TrainerEmail { get; set; }
}
I tried using the json2csharp tool with the response, and everything seems fine to my eyes:
public class Store
{
public int ID { get; set; }
public string ShortName { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string Phone { get; set; }
public string Lat { get; set; }
public string Long { get; set; }
public string GooglePlaceID { get; set; }
public string PropertyNumber { get; set; }
public int ManagerID { get; set; }
public int TrainerID { get; set; }
public string ManagerName { get; set; }
public string ManagerEmail { get; set; }
public object TrainerEmail { get; set; }
}
public class RootObject
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public List<Store> Stores { get; set; }
}
Any advice would be appreciated.
EDIT:
The RegisterViewModel class
public class RegisterViewModel
{
public RegistrationDTO regModel { get; set; }
public List<ManagerDTO> availableManager { get; set; }
public List<PropertyDTO> availableProperties { get; set; }
public List<TrainerDTO> availableTrainers { get; set; }
}
Make your controller Get() return type
IHttpActionResult
and return
Ok(dtoList);
I am writing an app for UWP.
I tried to use data binding according to this answer link.
Here are my classes:
public class Billing
{
public string first_name { get; set; }
public string last_name { get; set; }
public string company { get; set; }
public string address_1 { get; set; }
public string address_2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string postcode { get; set; }
public string country { get; set; }
public string email { get; set; }
public string phone { get; set; }
}
public class Shipping
{
public string first_name { get; set; }
public string last_name { get; set; }
public string company { get; set; }
public string address_1 { get; set; }
public string address_2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string postcode { get; set; }
public string country { get; set; }
}
public class RootObject
{
public int id { get; set; }
public int parent_id { get; set; }
public string status { get; set; }
public string order_key { get; set; }
public string currency { get; set; }
public string version { get; set; }
public bool prices_include_tax { get; set; }
public string date_created { get; set; }
public string date_modified { get; set; }
public int customer_id { get; set; }
public double discount_total { get; set; }
public double discount_tax { get; set; }
public double shipping_total { get; set; }
public double shipping_tax { get; set; }
public double cart_tax { get; set; }
public double total { get; set; }
public double total_tax { get; set; }
public Billing billing { get; set; }
public Shipping shipping { get; set; }
public string payment_method { get; set; }
public string payment_method_title { get; set; }
public string transaction_id { get; set; }
public string customer_ip_address { get; set; }
public string customer_user_agent { get; set; }
public string created_via { get; set; }
public string customer_note { get; set; }
public string date_completed { get; set; }
public string date_paid { get; set; }
public string cart_hash { get; set; }
public List<object> line_items { get; set; }
public List<object> tax_lines { get; set; }
public List<object> shipping_lines { get; set; }
public List<object> fee_lines { get; set; }
public List<object> coupon_lines { get; set; }
}
public ObservableCollection<RootObject> Orders { get; set; }
Here is the code:
List<RootObject> rootObjectData = JsonConvert.DeserializeObject<List<RootObject>>(products);
foreach (RootObject root in rootObjectData)
{
string date = root.date_created;
string name = root.billing.first_name + root.billing.last_name ;
Orders = new ObservableCollection<RootObject> { new RootObject { date_created = date,billing = name } };
}
With billing = name I have this error: Cannot implicitly convert type 'string' to 'Milano.InWork.Billing'
How can I fix this error?
Maybe this is simple, but I don't find a solution.
Thanks for the help!!
With billing = name I have this error: Cannot implicitly convert type 'string' to 'Milano.InWork.Billing'
Of course this error will occur, your billing in the class RootObject has the data type Billing, which is another class you defined.
Just from your code I think you only want to show the first_name and last_name as string in your root.billing, then you can change the code public Billing billing { get; set; } in your RootObject class to public string billing { get; set; }.
I have a the following classes
namespace MyClass.Models
{
public class Address : IIdentity
{
public string id { get; set; }
public DateTime updatedAt { get; set; }
public string user_id { get; set; }
public int building_number { get; set; }
public string street { get; set; }
public string area { get; set; }
public string county { get; set; }
public string country { get; set; }
public string postcode { get; set; }
public bool iscustomer { get; set; }
public bool islive { get; set; }
public string customer_id { get; set; }
public string store_id { get; set; }
public string phone_id { get; set; }
}
}
and
namespace MyClass.Models
{
public class User : IIdentity
{
public string id { get; set; }
public DateTime updatedAt { get; set; }
public string username { get; set; }
public string password { get; set; }
public bool isrestricted { get; set; }
public bool isbanned { get; set; }
public DateTime renewaldate { get; set; }
public string address_id { get; set; }
public string userlevel { get; set; }
}
}
What I am trying to do is create some test data to propagate through to my database so I can test my MVC5 website.
I am attempting to perform a look up on my instance of User within the Address class like so
user_id = context.User.FirstOrDefault(t=>t.address_id == id)
where id points to the id within the class I and trying instantiate.
VS2013 is saying that id does not exist in the current context which makes sense. Is there a way to do what I'm trying to achieve or am I better off setting the my _id from within the class itself and will that be okay when I run update-database from within the package manager console?
For example, the address class would become
namespace MyClass.Models
{
public class Address : IIdentity
{
public string id { get; set; }
public DateTime updatedAt { get; set; }
public string user_id { get {user_id = Users.FirstOrDefault(t=>t.address_id == id).id; } }
public int building_number { get; set; }
public string street { get; set; }
public string area { get; set; }
public string county { get; set; }
public string country { get; set; }
public string postcode { get; set; }
public bool iscustomer { get; set; }
public bool islive { get; set; }
public string customer_id { get {customer_id = Customers...;} }
public string store_id { get {store_id = Stores...;} }
public string phone_id { get {phone_id = Phones...;} }
}
}