gpt4 book ai didi

entity-framework - Entity Framework 4 v2 中的一对一关系与 POCO

转载 作者:行者123 更新时间:2023-12-04 12:25:40 25 4
gpt4 key购买 nike

我一直在寻找有关如何在 EF4v2 中与 POCO 建立一对一关系的示例。我找到了很多例子,只展示了如何创建一对多或多对多。你有任何关于它的资源吗?

最佳答案

这对我有用。

Database design

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>();
}

}

关于entity-framework - Entity Framework 4 v2 中的一对一关系与 POCO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2089395/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com