I've been looking for an example about how to build an one-to-one relationship in EF4v2 with POCO's. I found a lot of examples that show only how to create one-to-many or many-to-many. Do you have any resource about it?
You can create such a relationship by defining a third table, called a junction table, whose primary key consists of the foreign keys from both table A and table B.
Entity framework supports three types of relationships, same as database: 1) One-to-One 2) One-to-Many, and 3) Many-to-Many.
The DbContext class has a method called OnModelCreating that takes an instance of ModelBuilder as a parameter. This method is called by the framework when your context is first created to build the model and its mappings in memory.
This worked for me.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var myContext = new MyContext(@"Server=.\sqlexpress;Database=CodeFirst;integrated security=SSPI;");
var fr = new FirstReading() { Increment = 12};
myContext.Entry(fr).State = EntityState.Added;
myContext.SaveChanges();
var sr = new SecondReading() { Increment = 4 };
sr.FirstReading = fr;
myContext.SecondReading.Add(sr);
myContext.SaveChanges();
fr = myContext.FirstReading.Single(x => x.Increment == 12);
Console.WriteLine(fr.Increment);
Console.WriteLine(fr.SecondReading.Increment);
sr = myContext.SecondReading.Single(x => x.Increment == 4);
Console.WriteLine(sr.Increment);
Console.WriteLine(sr.FirstReading.Increment);
Console.ReadKey();
}
}
public class FirstReading
{
[Key][ForeignKey("SecondReading")]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int FirstReadingId { get; set; }
public int Increment { get; set; }
public virtual SecondReading SecondReading { get; set; }
}
public class SecondReading
{
[Key]
[ForeignKey("FirstReading")]
public int FirstReadingId { get; set; }
public int Increment { get; set; }
public virtual FirstReading FirstReading { get; set; }
}
public class MyContext : DbContext
{
public DbSet<FirstReading> FirstReading { get; set; }
public DbSet<SecondReading> SecondReading { get; set; }
public MyContext(string connectionString)
: base(connectionString)
{
Database.SetInitializer<MyContext>(null);
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
Look at Customer
-> CustomerDetail
in this example. This is 1:0..1, but I'm guessing that will do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With