簡體   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