Sunday, July 28, 2019

Use the proper annotations for objects in .NET Core's Code First Entity Framework stuff.

Consider these objects:

  1. using System;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    namespace FluffyNothing.Core.Objects
    {
       public class Game
       {
          [Key]
          [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
          public long GameId { get; set; }
          public long Player1 { get; set; }
          [Required]
          public string Player1Hand { get; set; }
          public DateTime Player1Time { get; set; }
          public long? Player2 { get; set; }
          public string Player2Hand { get; set; }
          public DateTime? Player2Time { get; set; }
       }
    }
     
  2. using System;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    namespace FluffyNothing.Core.Objects
    {
       public class Message
       {
          [Key]
          [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
          public long MessageId { get; set; }
          [Required]
          [ForeignKey("PlayerId")]
          public Player Player { get; set; }
          [Required]
          public string Copy { get; set; }
          public DateTime Time { get; set; }
       }
    }
     
  3. using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    namespace FluffyNothing.Core.Objects
    {
       public class Player
       {
          [Key]
          [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
          public long PlayerId { get; set; }
          [Required]
          [MaxLength(15)]
          public string PlayerIp { get; set; }
          public virtual ICollection<Message> Messages { get; set; }
       }
    }
     

It makes this at the database:

Things to note here include how to make a parent/child relationship, how to make a varchar be a specific width, and how making a varchar not nullable takes a different shape than that of other types. In the case of long and DateTime we just either have a nullable type at the C# side or we don't, right? In the case of string we have to use the Required attribute. I guess this much will change in C# 8 with the introduction of nullable strings.

No comments:

Post a Comment