Last active
December 21, 2015 05:48
-
-
Save eralston/6259123 to your computer and use it in GitHub Desktop.
Example C# class showing the basic and recurring patterns of fields used in Code First Entity Framework
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.ComponentModel.DataAnnotations; | |
using System.ComponentModel.DataAnnotations.Schema; | |
using System.Data.Entity; | |
using System.Globalization; | |
using System.Linq; | |
using System.Web.Security; | |
class Example | |
{ | |
// Primary Key | |
[Key] | |
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] | |
public int Id { get; set; } | |
[Display(Name = "Created Date")] | |
public DateTime? CreatedDate { get; set; } | |
// Required Field | |
[Required] | |
public string Title { get; set; } | |
// Tweet text | |
[MaxLength(140)] | |
public string Tweet { get; set; } | |
// To-Many on Post | |
public virtual ICollection<Post> Posts { get; set; } | |
// To-One on Author | |
[ForeignKey("Author")] | |
public int AuthorId { get; set; } | |
public virtual Author Author { get; set; } | |
[Display(Name = "E-Mail")] | |
[EmailAddress] | |
public string Email { get; set; } | |
[DataType(DataType.MultilineText)] | |
public string Body { get; set; } | |
} | |
public static class ExampleExtensions | |
{ | |
public static Example Create(this DbSet<Example> examples) | |
{ | |
Example ex = new Example(); | |
ex.CreatedDate = DateTime.Now; | |
// Set Fields | |
examples.Add(ex); | |
return ex; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment