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?
问问题
3386 次
3 回答
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>();
}
}
于 2011-11-12T06:25:40.550 回答
1
看看这个例子中的Customer
-> 。这是 1:0..1,但我猜会这样。CustomerDetail
于 2010-01-18T21:47:43.147 回答
1
搜索这个
How to declare one to one relationship using Entity Framework 4 Code First (POCO)
或者
看看这个链接
于 2013-06-12T12:42:49.253 回答