EF Code First中的零对一关系

时间:2017-05-06 03:47:29

标签: c# entity-framework ef-code-first

我有2个像下面这样的实体;

File's Owner

我首先创建订单。

  1. 根据订单,我可以创建购买。
  2. 购买也可以在没有订单的情况下进行。所以它是Nullable外键。
  3. 对于一个订单,它应该只有一次购买。所以OrderId也是独一无二的。
  4. 如何在Code First中指定此关系

1 个答案:

答案 0 :(得分:1)

可以指定这样的唯一属性。您无法在EF6中将唯一索引作为外键的目标。

public class Order
{
    public int Id { get; set; }
    public string Description { get; set; }
    public virtual Purchase Purchase { get; set; }
}

public class Purchase
{
    public int Id { get; set; }
    public string Description { get; set;}

    [Index(IsUnique = true)]
    public int? OrderId { get; set; }
    public virtual Order Order { get; set; }
}

但EF不会允许与非键列的1-1关系,但这样的事情具有所需的关系模型:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp5
{
    public class Order
    {
        public int Id { get; set; }
        public string Description { get; set; }
        internal ICollection<Purchase> Purchases { get; } = new HashSet<Purchase>();
        public Purchase Purchase { get { return Purchases.FirstOrDefault(); } }
    }

    public class Purchase
    {
        public int Id { get; set; }
        public string Description { get; set; }

        [Index(IsUnique = true)]
        public int? OrderId { get; set; }

        [ForeignKey("OrderId")]
        public virtual Order Order { get; set; }
    }

    public class Db : DbContext
    {
        public DbSet<Order> Orders { get; set; }
        public DbSet<Purchase> Purchases { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Order>().HasMany(o => o.Purchases).WithOptional(p => p.Order);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Database.SetInitializer(new DropCreateDatabaseAlways<Db>());
            int OrderId;
            using (var db = new Db())
            {

                var o = db.Orders.Create();
                o.Description = "New Order";

                var p = db.Purchases.Create();
                p.Order = o;
                p.Description = "New Purchase";


                db.Orders.Add(o);
                db.Purchases.Add(p);
                db.SaveChanges();
                OrderId = o.Id;

            }
            using (var db = new Db())
            {
                var p = db.Purchases.Create();
                p.OrderId = OrderId;
                p.Description = "Another Purchase";
                db.Purchases.Add(p);
                db.SaveChanges(); //fails

            }
        }
    }
}

大卫