我一直在寻找一个关于如何在EF4v2中用POCO构建一对一关系的例子。我发现很多例子只显示如何创建一对多或多对多。你有资源吗?
答案 0 :(得分:3)
这对我有用。
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>();
}
}
答案 1 :(得分:1)
查看Customer
- &gt; this example中的CustomerDetail
。这是1:0..1,但我猜这样做。
答案 2 :(得分:1)
搜索此
How to declare one to one relationship using Entity Framework 4 Code First (POCO)
或
查看此链接
How to declare one to one relationship using Entity Framework 4 Code First (POCO)