Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Thealexbarney/2cfec11d8cbd211ff89e8dad51798248 to your computer and use it in GitHub Desktop.
Save Thealexbarney/2cfec11d8cbd211ff89e8dad51798248 to your computer and use it in GitHub Desktop.
using System;
using System.Linq;
using Microsoft.Data.Entity;
namespace Test
{
public static class Program
{
static void Main(string[] args)
{
using (var db = new Context())
{
var a = new A
{
Field1 = 13
};
db.Add(a);
var b = new B
{
Field1 = 14
};
a.B = b;
db.SaveChanges();
var result = db.As.First();
Console.WriteLine(result.BId ?? -1);
}
}
public class Context : DbContext
{
public DbSet<A> As { get; set; }
public DbSet<B> Bs { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseInMemoryDatabase();
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<B>(entity =>
{
entity.HasOne(d => d.A)
.WithOne(p => p.B)
.HasForeignKey<A>(k => k.BId);
});
}
}
public class A
{
public int Id { get; set; }
public int Field1 { get; set; }
public int? BId { get; set; }
public B B { get; set; }
}
public class B
{
public int Id { get; set; }
public int Field1 { get; set; }
public A A { get; set; }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment