繁体   English   中英

实体框架:添加到新实体时,如何使用来自实体B的自动生成ID作为实体A中的外键?

[英]Entity framework: When adding to new entities, how to use autogen ID from entity B as foreign key in entity A?

我有两个实体,其中实体A具有到实体B的外键。实体PK在DB中自动生成。 当我为每个实体创建一个新对象并将实体A链接到B时,我希望SaveChanges()在保存实体B之后并在保存实体A之前更新实体A中的外键,但这不会发生-我期望太多了? 我必须使用两次SaveChanges()调用吗?

码:

public class Product
{
  [Key]
  public int ProductId { get; set; }

  [Required]
  public int ProductTypeId { get; set; }

  [ForeignKey("ProductTypeId")]
  public virtual ProductType ProductTypeRef { get; set; }
}

public class ProductType
{
  [Key]
  public int ProductTypeId { get; set; }
}

Product product = new Product();
product.ProductTypeRef = new ProductType();
_context.Products.Add(product);
_context.SaveChanges();  // leads to exception telling foreign key constraint not met

这对我来说很好:

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

namespace Ef6Test
{

    public class Product
    {
        [Key]
        public int ProductId { get; set; }

        [Required]
        public int ProductTypeId { get; set; }

        [ForeignKey("ProductTypeId")]
        public virtual ProductType ProductType { get; set; }
    }

    public class ProductType
    {
        [Key]
        public int ProductTypeId { get; set; }
    }


    class Db : DbContext
    {


        public DbSet<Product> Products { get; set; }
        public DbSet<ProductType> ProductTypes { get; set; }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {

            Database.SetInitializer(new DropCreateDatabaseAlways<Db>());

            using (var db = new Db())
            {
                Product product = new Product();
                product.ProductType = new ProductType();
                db.Products.Add(product);
                db.SaveChanges();  // works fine
            }

            Console.WriteLine("Hit any key to exit");
            Console.ReadKey();
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM