Home > other >  c# getting suitable field from database by languages in linq connect model
c# getting suitable field from database by languages in linq connect model

Time:12-01

I am using dotConnect for MySQL product of Devart. MySQL database structure likes this:

enter image description here

I am getting data like this:

public int user_id { get; set; } = 2;
public string lang { get; set; } = "en"; // Depending on the situation, it may also be "tr".
private readonly mainDataContext _db = new();

var cats = _db.categories.Where(s => s.u_id == user_id);
foreach (var cat in cats)
{
    MessageBox.Show(cat.name_en);
}

In the MessageBox.Show I can not use cat.name "_" lang like PHP. I don't know how to get over this problem.

CodePudding user response:

In nutshell, you can use this:

cat.GetType().GetProperty("name_"   lang).GetValue(cat,null))

But it's better to call a method to get value:

static public T getval<T>(Object obj, string field)
        {
            return (T)obj.GetType().GetProperty(field).GetValue(obj, null);
        }

Here is a full example:

using System;

namespace Example
{
    public class user
    {
        public int user_id { get; set; } = 2;
        public string name_en { get; set; }
        public string name_tr { get; set; }

       
    }
    
    class Program
    {
        static public T getval<T>(Object obj, string field)
        {
            return (T)obj.GetType().GetProperty(field).GetValue(obj, null);
        }
        static void Main(string[] args)
        {

            List<user> u = new List<user>();
            u.Add(new user { user_id = 1, name_en = "Foods", name_tr = "name_tr value 1" });
            u.Add(new user { user_id = 2, name_en = "Pizza", name_tr = "name_tr value 2" });
            u.Add(new user { user_id = 2, name_en = "Other", name_tr = "name_tr vale 3" });
            var lang = "en";
            var cats = u.Where(s => s.user_id == 2);
            foreach (var cat in cats)
            {
                Console.WriteLine(getval<string>(cat,"name_" lang));
            }
            return;
        }
    }
}
  • Related