Issue when inserting Chinese data with code first and mysql - mysql

I've done a project in ASP.NET MVC 3 using Mysql. To create a database, I use code first ef 4.1. Some of the data I insert in my database is Chinese characters. When I insert the data, it appears with ????. I set my connectionString in my web config like this:
add name="mydbcontext" connectionString="server=localhost;user id=root; password=; database=mydbcontext; pooling=false; charset=utf8;" providerName="MySql.Data.MySqlClient"
But the problem's still there... This is the way I use to insert the data:
public class MyMenu {
public int Id { get; set; }
public string Home { get; set; }
public string About { get; set; }
public string AppForSmartphone { get; set; }
public string Games { get; set; }
public string Softwares { get; set; }
public string Language { get; set; }
public string News { get; set; }
public string Cart { get; set; }
}
public class MyDbContext : DbContext {
public DbSet<MyMenu> MyMenus { get; set; }
public MyDbContext()
: base("MyDbContext") {
}
}
private MyDbContext db = new MyDbContext();
MyMenu tmpmenu = new MyMenu {
About = 關於,
Id = 1,
Cart = 車,
News = 新聞,
AppForSmartphone = 應用程序的智能手機,
Games = 遊戲,
Softwares = 軟件,
Home = 家,
Language = ""
};
db.MyMenus.Add(tmpmenu);
db.SaveChanges();
Can someone help me?

There is no Issue in your code.You just need to check the DataType of the column in which you are saving the data which is in Chinese.I guess you have used varchar() , rather you should be using nvarchar().
I had the same issue a day back. And changing the datatype to nvarchar() fixed my issue.
MySql does support multilingual.
Changing the DataType should fix your issue.
Regards.

Related

Dotnet Core DB Scaffold creates additional Collections for Object

I have a Mysql Database and want to create a scaffold to try a data-first .net project. I got the scaffold to work, which was great, but it is creating these false Collections on my model objects for related tables.
For my coin object below, I only have the 5 fields on the top, but it is creating the collections to any of the tables where Coin is a foreign key. This is not really making any sense to me. I will never populate this data and cannot see any settings to stop this from happening.
public partial class Coin
{
public Coin()
{
LedgerTransactions = new HashSet<LedgerTransactions>();
Price = new HashSet<Price>();
TradeFeeCoin = new HashSet<Trade>();
TradeForCoin = new HashSet<Trade>();
TradeTradeCoin = new HashSet<Trade>();
}
[Column(TypeName = "int(11)")]
public int Id { get; set; }
[Required]
[StringLength(50)]
public string Name { get; set; }
[Required]
[StringLength(5)]
public string Symbol { get; set; }
public byte? SortOrd { get; set; }
[Column(TypeName = "bit(1)")]
public bool? IsBaseCurrency { get; set; }
[InverseProperty("Coin")]
public ICollection<LedgerTransactions> LedgerTransactions { get; set; }
[InverseProperty("Coin")]
public ICollection<Price> Price { get; set; }
[InverseProperty("FeeCoin")]
public ICollection<Trade> TradeFeeCoin { get; set; }
[InverseProperty("ForCoin")]
public ICollection<Trade> TradeForCoin { get; set; }
[InverseProperty("TradeCoin")]
public ICollection<Trade> TradeTradeCoin { get; set; }
}
I created this table from a Code-First approach, and that model only had the 5 fields in it that I would expect. Am I doing something wrong?

Return a non-mapped Entity property based on a SUM of child records in the EntityFramework

Using an example, I have the following two Entities. The OrderEntity contains a collection of OrderLineEntites
public class OrderEntity
{
public string Reference { get; set; }
public string Description { get; set; }
public bool Confirmed { get; set; }
[NotMapped]
public int OrderLineCount { get; set; }
[InverseProperty("Order")]
public virtual ICollection<OrderLineEntity> OrderLineEntity__OrderEntity { get; set; }
}
public class OrderLineEntity
{
public string Name { get; set; }
public string Description { get; set; }
}
Using the following code I can load all the OrderLineEntities for all confirmed orders.
DbSet<OrderEntity> orderEntity.Where(x => x.Confirmed).Include(x => x.OrderLineEntity__OrderEntity)
What I need to do is set the non-mapped OrderLineCount property with the Count of the OrderLine records (to save actually loading them).
So for each loaded Order I have a fully populated Entity including the [NotMapped] property with an empty OrderLine collection.
Advise would be appreciated :)
Thanks
You can do this, but you have to change your approach. You have to manually map the objects yourself:
var query = from a in context.Orders.Where(x => x.Confirmed)
select new OrderEntity
{
Reference = a.Reference,
Description = a.Description,
Confirmed = a.Confirmed,
OrderLineCount = a.OrderLineEntity__OrderEntity.Count
};
return query.ToList();

An Error Occurred While serializing to JSON

Hi firends i'm getting error when i tried to Serialize JSON. I have a model and it have List property;
MyModel:
public virtual int Kod { get; set; }
public virtual string Ad { get; set; }
public virtual string TrafikKod { get; set; }
public virtual int TapuKod { get; set; }
public virtual bool AktifMi { get; set; }
[JsonIgnore]
public virtual IList<TapuIlceModel> IlceList { get; set; }
public TapuIlModel()
{
IlceList = new List<TapuIlceModel>();
}
MyApiController:
[Route("api/TapuZeminApi/GetZemins")]
[HttpPost]
public string GetZeminsFromZeminArg(object arg)
{
ZeminArg zemArg = SConvert.DeserializeJSON<ZeminArg>(arg.ToString());
List<TapuZeminModel> zeminList = TapuModule.GetZeminListFromArgs(zemArg);
string jsonResult = SConvert.SerializeJSON(zeminList);
return jsonResult;
Here is a picture about my reciving data error;
And this my inner exc.;
.{"Error getting value from 'ReadOnly' on 'NHibernate.Proxy.DefaultLazyInitializer'."}
.{"Proxy is detached (i.e, session is null). The read-only/modifiable setting is only accessible when the proxy is associated with an open session."}
What should i do? I need all data... Thanks
when i check again i found something like that:
Why is there 2 base??? And why name is different? Anyone know?
I geting same error when serilize SerializeJSON(object) , i have try JsonConvert.SerializeObject with JsonSerializerSettings and ContractResolver, it will work.
string jsonResult = JsonConvert.SerializeObject(object, new JsonSerializerSettings() {
ContractResolver = new NHibernateContractResolver()
});

Web API Json Serialization Exception & Dynamic Entities

I have a web API controller method that is returning an object which is giving the client a 500 internal server error. On the server, the output windows says "Newtonsoft.Json.JsonSerializationException". But I cannot see anything wrong with the class I am returning.. and I am sure this has historically been working. Any help would be greatly appreciated!
EDIT: Is this a problem with the web API not being able to serialize a 'dynamic entity'? The code that generates the class is here:
var id = User.Identity.GetUserId();
var user = db.Users
.Where(u => u.Id == id)
.Include(u => u.Friends)
.FirstOrDefault();
return user;
I am returning the following class;
public class User : IdentityUser
{
public User()
{
this.Friends = new List<UserFriend>();
}
public string PhoneNumber { get; set; }
public string Email { get; set; }
public List<UserFriend> Friends { get; set; }
public bool HasRegistered { get; set; }
public string LoginProvider { get; set; }
}
The 'UserFriend' class looks like this;
public class UserFriend
{
public int UserFriendId { get; set; }
public string Id { get; set; }
public string FriendUserId { get; set; }
public string FriendUserName { get; set; }
public string FriendPhoneNumber { get; set; }
}
Strangely, when I hover over the returned object on the server, the type is: {System.Data.Entity.DynamicProxies.User_7283E76A736B4DD47E89120E932CD5C04B62F84C316961F02CDAE3EEF4786504}. I am not sure what this is.. :-O
I used AutoMapper to create a DTO instead of just returning the User class. The DynamicProxies class is because the query uses lazy loading and it has not got the object yet.
After installing automapper (Install-Package AutoMapper);
Mapper.CreateMap<User, UserDto>();
UserDto dto = Mapper.DynamicMap<UserDto>(user);
Then return the dto.

Code First Object not properly instantiating

I have a class department inheriting from activeentity
public class ActiveEntity : Entity, IActive
{
public ActiveEntity()
{
IsActive = true;
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public Guid Id { get; set; }
public bool IsActive { get; set; }
[Timestamp, ScaffoldColumn(false), DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.Computed)]
public Byte[] Timestamp { get; set; }
[ScaffoldColumn(false)]
public string CreationUserId { get; set; }
[ScaffoldColumn(false)]
public string LastModifiedUserId { get; set; }
}
public class Department:ActiveEntity
{
public Department()
{
this.Address = new DepartmentAddress();
}
[StringLength(9),MinLength(9),MaxLength(9)]
public string Name { get; set; }
public Guid ManagerId { get; set; }
[UIHint("AjaxDropdown")]
public User Manager { get; set; }
public Guid? AddressId { get; set; }
public DepartmentAddress Address { get; set; }
public ICollection<OverheadRate> OverheadRates { get; set; }
}
I am just using annotations no Fluent API. The data saves to the data Sql Server 2008 just fine however the address object never gets instantiated, even though I have the context use the include
return c.Set<Department>().Include(d => d.Address).Include(d => d.Manager).Where(predicate);
The data is returned I run sql profiler and then run the query it returns the correct data.
Any thoughts or suggestions?
Remove instantiating the address (this.Address = new DepartmentAddress();) in the Department constructor. Instantiating navigation references in the default constructor is evil and has nasty side effects like these:
What would cause the Entity Framework to save an unloaded (but lazy loadable) reference over existing data?
EF 4.1 Code First: Why is EF not setting this navigation property?