Skip to content

Example.Map_Class

IzayoiJiichan edited this page Aug 31, 2024 · 3 revisions

Examples

Map Classes

using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

//[Table("users")]
[Table("users", Schema = "dbo")]
public class User
{
    [Key]
    [Column("id")]
    public int Id { get; set; }

    [Column("name")]
    public string Name { get; set; } = string.Empty;

    [Column("age")]
    public byte Age { get; set; }

    [Column("gender")]
    public GenderType Gender { get; set; }

    [Column("created_at")]
    public DateTime CreatedAt { get; set; }

    [Column("updated_at")]
    public DateTime UpdatedAt { get; set; }

    [NotMapped]
    public int IgnoreProperty { get; set; }
}

//[Table("posts")]
[Table("posts", Schema = "dbo")]
public class Post
{
    [Key]
    [Column("id")]
    public int Id { get; set; }

    [Column("posted_at")]
    public DateTime PostedAt { get; set; }

    [Column("user_id")]
    public int UserId { get; set; }

    [Column("comment")]
    public string Comment { get; set; } = string.Empty;
}

public class PostCount
{
    [Column("user_id")]
    public int UserId { get; set; }

    [Column("user_name")]
    public string UserName { get; set; } = string.Empty;

    [Column("count")]
    public int Count { get; set; }
}

//[Table("items")]
[Table("items", Schema = "dbo")]
public class Item
{
    [Key]
    [Column("id")]
    public Guid Id { get; set; }

    [Column("name")]
    public string Name { get; set; } = string.Empty;

    [Column("created_at")]
    public DateTime CreatedAt { get; set; }

    [Column("updated_at")]
    public DateTime UpdatedAt { get; set; }
}
  • If the [Table] attribute is not defined, the class name is used as the table name.
  • If the [Column] attribute is not defined, the property name is used as the column name.
  • If the [NotMapped] attribute is defined, the property is excluded from the mapping.
  • The [Key] attribute is set to the primary key. It is used for update or delete methods.