• ุงุชูƒู„ู…ู†ุง ู‚ุจู„ ูƒุฏุง ุนู† ุงู„ู€ Type Casting in CSharp ูˆู‚ูˆู„ู†ุง ู†ุจุฐู‡ ุนู†ู‡ ุจุฑุถูˆ ููŠ ุงู„ู€ Not Binding

Manual Mapping (Build-in Casting Operator)

ุงุญู†ุง ุงุชูƒู„ู…ู†ุง ุนู† ุงู„ู€ code-first

  • ุจู†ุจู†ูŠ ุฃูˆู„ ุญุงุฌุฉ ุงู„ู€ class ุจุชุงุนูŠ ุนุงุฏูŠ
  • ุฏุง ุงู„ู€ Model ูˆู‡ู†ุง ุงู„ู€ Class ุจูŠู…ุซู„ Table ููŠ ุงู„ู€ Database
// Model : is the Class that represents the table in the database
class User
{
    public int Id { get; set; }
    public string FullName { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
    public string SecurityStamp { get; set; }
}
  • ูŠุนู†ูŠ ุงุญู†ุง ุฏู„ูˆู‚ุชูŠ ุจู†ุชูƒู„ู… ุนู† ุดูƒู„ ุงู„ู€ Data ููŠ ุงู„ู€ Database
  • ุจุณ ู…ุด ุฏุง ุงู„ู„ูŠ ุจูŠุธู‡ุฑ ู„ู„ู€ Users ุจุชุงุน ุงู„ู…ูˆู‚ุน
  • ูุนุดุงู† ูƒุฏุง ู„ุงุฒู… ุจู†ุนู…ู„ Class ุชุงู†ูŠ ูˆุจูŠุจู‚ุง ุงุณู…ู‡ ุงู„ู€ View Model
class UserViewModel
{
    public int Id { get; set; }
    public string Fname { get; set; }
    public string Lname { get; set; }
    public string Email { get; set; }
}
  • ุฏู„ูˆู‚ุชูŠ ู‡ูŠุธู‡ุฑ ู…ุดูƒู„ุฉ ุฅู†ูŠ ุงู„ู…ูุฑูˆุถ ู‡ุงุฎุฏ ู…ู† ุงู„ู€ Database ุงู„ู€ Object ู…ู† ุงู„ู†ูˆุน User
  • ูˆุนุดุงู† ุฃุธู‡ุฑู‡ุง ูˆุฃุญูˆู„ู‡ุง ุงู†ู‡ุง ุชุธู‡ุฑ ู„ู„ู€ HTML ู„ุงุฒู… ุฃุญูˆู„ู‡ุง ู„ู„ู€ Class ุงู„ู„ูŠ ู‡ูŠุฑุฌุน ู†ูุณู‡ ุงู„ู„ูŠ ู‡ูˆ ุงู„ู€ View Model
  • ุจุณ ู…ูŠู†ูุนุด ุฃุฎู„ูŠ reference ู…ู† Class ูŠุดุงูˆุฑ ุนู„ู‰ Object ู„ู€ Class ุชุงู†ูŠ ู…ู† ุบูŠุฑ ู…ุง ุฃุนู…ู„ Casting
    • ูˆุฒูŠ ู…ุง ุนุฑูู†ุง ุนู†ุฏู†ุง ู†ูˆุนูŠู† ู…ู† ุงู„ู€ Casting ุงู„ู„ูŠ ู‡ู…ุง ุงู„ู€ Implicit ูˆุงู„ู€ Explicit
  • ุจุณ ููŠ ุงู„ุญุงู„ุฉ ุฏูŠ ู„ุงุฒู… ู„ูˆ ุญุงุฌุฉ ู…ุด ู…ุนู…ูˆู„ุฉ Built-in ุงู†ูŠ ุฃุนู…ู„ู‡ุง ุจุฅูŠุฏูŠ
// MAIN
User user1 = new User()
{
    Id = 1,
    FullName = "Pop Corn",
    Password = "Password",
    Email = "pop.corn@me.com",
    SecurityStamp = Guid.NewGuid().ToString()
};
// UserViewModel userViewModel = user1; // ERROR
// We should do Casting (Mapping)
UserViewModel userViewModel = (UserViewModel)user1;
// It's also will give me ERROR, we should implement it
  • ุนุดุงู† ู†ุนู…ู„ Explicit operator ุจุฑูˆุญ ู„ู„ู€ class ุงู„ุชุงู†ูŠ ุงู„ู„ูŠ ู‡ูˆ ุงู„ู€ view
  • ุงู„ู€ Model ุงู„ุฃุตู„ูŠ ุฏุง ู…ู…ูƒู† ู†ุณู…ูŠู‡ Poco class
public static explicit operator UserViewModel(User user)
{
    string[] names = user.FullName.Split(' ');
    return new UserViewModel()
    {
        Id = user.Id,
        Fname = names[0],
        Lname = names[1],
        Email = user.Email
    };
}