实体框架 – 实体框架4 v2中与POCO的一对一关系

我一直在寻找一个关于如何在EF4v2中与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>();
  }

}

转载注明原文:实体框架 – 实体框架4 v2中与POCO的一对一关系 - 代码日志