【问题标题】:one to one entity framework一对一实体框架
【发布时间】:2012-03-09 14:51:11
【问题描述】:

有没有人知道绑定和插入一对一实体的好例子

我想绑定并能够使用实体框架在单个 winform 中对两个表进行更改。

此客户表单将包含来自个人实体和客户实体的数据 个人实体将具有名字和姓氏,而客户实体将具有加入日期等...

这是一对一的关系。

【问题讨论】:

  • 谷歌:ef 一对一的关系
  • 我用谷歌搜索过,没有找到我需要的东西。当我从数据源拖放到 Winforms Customer 对象时,我还将 Person 对象作为详细信息拖到表单中,但在运行时没有任何反应。这就是我在加载事件上绑定它的方式。 Me.CustomerBindingSource.DataSource = context.Customers.ToList

标签: .net sql winforms entity-framework


【解决方案1】:

只需在Person 中使用virtual Customer 属性。 无需在Customer 中添加引用。

请在下面找到一个完整的项目

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;

namespace StackOverflow
{

    public class Context : DbContext
    {
        static Context()
        {
            Database.SetInitializer<Context>(null);
        }

        public DbSet<Person> People { get; set; }
    }


    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string LastName { get; set; }
        public virtual Customer Customer { get; set; }
    }

    public class Customer
    {
        public int Id { get; set; }
        public DateTime JoinDate { get; set; }
        //[NotMapped]
        //public virtual Person Person { get; set; }
    }



    class Program
    {
        static void Main(string[] args)
        {
            var context = new Context();
            context.Database.Delete();
            context.Database.Create();

            var person = new Person { Name = "Mark", LastName = "Streisand" };
            person.Customer = new Customer { JoinDate = DateTime.Now };
            context.People.Add(person);
            context.SaveChanges();

            var p = context.People.Find(1);
            var joinDate = p.Customer.JoinDate;
        }
    }
}

附言。实际上,我相信你的场景可以用抽象的Person 类继承的Customer 更好地设计。 在这种情况下,您不需要在Person 中对Customer 进行任何引用,因为Customer 本身就是Person 的一个实例。这将允许您拥有多个Person 的实现,所有这些实现都映射到不同的表。

看看这个sn-p

    public abstract class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string LastName { get; set; }
        //public virtual Customer Customer { get; set; }
    }

    [Table("Customers")]
    public class Customer : Person
    {
        //public int Id { get; set; }
        public DateTime JoinDate { get; set; }

    }

【讨论】:

    猜你喜欢
    • 2021-09-02
    • 1970-01-01
    • 1970-01-01
    • 2016-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多