entityframework上下文中的实体是什么?

时间:2014-08-22 16:07:32

标签: c# entity-framework

我想使用EntityFramework.BulkInsert实现此操作,我检查了文档,但我是EF的新手,我无法弄清楚这个上下文中的实体是什么。实体是什么?

foreach (string tag in tags)
    {
        TagUser tagUser = new TagUser()
        {
            //Initialize TagUser
        };


        applicationUser.TagUsers.Add(tagUser);
    }

db.SaveChanges();

这是其文档中的示例代码:

using (var ctx = GetContext())
{
  using (var transactionScope = new TransactionScope())
  {
    // some stuff in dbcontext

    ctx.BulkInsert(entities);

    ctx.SaveChanges();
    transactionScope.Complete();
  }
}

这是我的TagUserclass:

public class TagUser
    {
        [Required]
        [Key, Column(Order = 0)]
        [ForeignKey("Tag")]
        public Guid TagId { get; set; }

        [Required]
        [Key, Column(Order = 1)]
        [ForeignKey("ApplicationUser")]
        public string Id { get; set; }


        public virtual Tag  Tag { get; set; }


        public virtual ApplicationUser ApplicationUser { get; set; }


        [Required]
        public bool InEnglish { get; set; }

        [Required]
        public Int16 Priority { get; set; }

    }

2 个答案:

答案 0 :(得分:1)

在此上下文中,entities将是您尝试插入的实体列表。因此,不是每次都说TagUsers.Add(taguser),而是可以获得要在List<TagUser> tagusers中插入的TagUser列表(也许是这样,我没有亲自使用过BulkInsert),并说{{1} }

答案 1 :(得分:1)

实体是标签用户集合,在进行批量插入之前,首先提供FK ID。

using (var ctx = GetContext())
{
    using (var transactionScope = new TransactionScope())
    {
        var entities= new List<TagUser>();
        foreach (string tag in tags)
        {
            TagUser tagUser = new TagUser()
            {
                //Initialize TagUser
                TagId = ..., // get something like tag.Id
                Id = applicationUser.Id
            };
            entities.Add(tagUser);
        }

        ctx.BulkInsert(entities);

        ctx.SaveChanges();
        transactionScope.Complete();
    }
}
相关问题