开发者

one-to-one relationships in Entity Framework 4 v2 with POCO

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-开发者_JAVA技巧to-many. Do you have any resource about it?


This worked for me.

one-to-one relationships in Entity Framework 4 v2 with POCO

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.


search this

How to declare one to one relationship using Entity Framework 4 Code First (POCO)

or

look at this link

How to declare one to one relationship using Entity Framework 4 Code First (POCO)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜