本文介绍了4 V2与POCO实体框架中的一比一的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找如何构建一个一对一关系的EF4v2与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-to-many. Do you have any resource about it?

推荐答案

这为我工作。

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实体框架中的一比一的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 15:43