Entity Framework一對多關係添加數據的兩種方式

 

當使用Entity Framework添加一對多關係數據的時候,一般先添加一的數據,而後再添加多的數據。相似這樣:數據庫

 

//添加一的數據
var category = new Category{Name="類別1"};
category = context.Categories.Add(category);

//添加多的數據
for(var i = 0; i < 2; i++)
{
    context.Products.Add(new Product{
        Name = "產品" + i,
        CategoryId = category.Id});
}

context.SaveChanges();

 

以上,咱們對Category和Product分別進行了Add操做,而後統一SaveChanges。是否能夠對Category的Products屬性賦值,只對Catetegory進行Add,而後SaveChanges呢?

也就是按以下:ide

 

var category = new Category{Name="類別1"};
for(var i = 0; i < 2; i++){
    category.Products.Add(new Product{
        Name="產品" + i,
        Category = category
    });
}
context.Categories.Add(category);
context.SaveChanges();

 

那就驗證下。

來兩個一對多關係的領域模型。spa

 

    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public int CategoryId { get; set; }
        public virtual Category Category { get; set; }
    }

    public class Category
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public virtual ICollection<Product> Products { get; set; }

        public Category()
        {
            Products = new List<Product>();
        }
    }

 

建立上下文:code

 

    public class EFTestContext: DbContext
    {
        public EFTestContext() : base("conn")
        {

        }

        public DbSet<Category> Categories { get; set; }
 
    }

 

配置鏈接字符串:blog

 

  <connectionStrings>
    <add name="conn"
       connectionString="Data Source=.;User=YourUsername;Password=YourPassword;Initial Catalog=EFTest;Integrated Security=True"
       providerName="System.Data.SqlClient"/>
  </connectionStrings>  

 

客戶端程序:字符串

 

        static void Main(string[] args)
        {
            using (var context = new EFTestContext())
            {
                var category = new Category
                {
                    Name = "產品類別3"
                };
                
                for(var i=0;i<2;i++)
                {
                    category.Products.Add(new Product {
                        Name = "產品" + i,
                        //Category = category
                        CategoryId = category.Id
                    });
                }

                context.Categories.Add(category);
                context.SaveChanges();
            }

            Console.WriteLine("運行結束");
            Console.ReadKey();
        }

 

運行成功。get



總結:當使用Entity Framework添加一對多關係數據的時候,咱們經過給一的集合屬性賦值,只context.表明一的表s.Add(表明一的實例),也一樣能夠在數據庫中爲表明多的那個表添加數據。而且,表明多的那個DbSet不設置也行。string

相關文章
相關標籤/搜索