Created
December 12, 2013 05:00
-
-
Save trayburn/7923392 to your computer and use it in GitHub Desktop.
EF Type per Hierarchy with Required example
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.Data.Entity; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace ConsoleApplication2 | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var context = new ExampleContext(); | |
context.BaseClasses.Add(new Snafu() { Whatever = 123 }); | |
context.BaseClasses.Add(new Foobar() { Whatever = 123 }); | |
context.SaveChanges(); | |
foreach (var item in context.BaseClasses.OfType<Snafu>()) | |
{ | |
Console.WriteLine(item.Whatever); | |
} | |
foreach (var item in context.BaseClasses.OfType<Foobar>()) | |
{ | |
Console.WriteLine(item.Whatever); | |
} | |
Console.ReadLine(); | |
} | |
} | |
public class ExampleContext : DbContext | |
{ | |
public DbSet<BaseClass> BaseClasses { get; set; } | |
protected override void OnModelCreating(DbModelBuilder modelBuilder) | |
{ | |
modelBuilder.Entity<BaseIntermediaryClass>().Property(fb => fb.Whatever).HasColumnName("Whatever"); | |
base.OnModelCreating(modelBuilder); | |
} | |
} | |
public class BaseClass | |
{ | |
public int Id { get; set; } | |
} | |
public abstract class BaseIntermediaryClass : BaseClass | |
{ | |
[Required] | |
public int Whatever { get; set; } | |
} | |
public class Foobar : BaseIntermediaryClass | |
{ | |
} | |
public class Snafu : BaseIntermediaryClass | |
{ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment