oracle 在实体框架中添加记录列表失败

hgqdbh6s  于 2023-10-16  发布在  Oracle
关注(0)|答案(1)|浏览(96)

我尝试使用Entity Framework向数据库添加实体,但失败了。下面是负责向数据库添加实体列表的源代码:

public class EfUserPermissionRepository : IUserPermissionDal
{

    private readonly EfDbContext _context;

    public EfUserPermissionRepository(EfDbContext context)
    {
        if (context == null)
            throw new ArgumentNullException(typeof(EfDbContext).ToString());

        this._context = context;
    } 

    //It adds USERPERMISSION list to database. 
    public void Add(List<USERPERMISSION> entities)
    {

        try
        {
            if (entities == null || !entities.Any())
                throw new ArgumentNullException();

            foreach (USERPERMISSION value in entities)
            {

                if (value == null)
                    continue;

                this._context.USERPERMISSION.Add(value);
            }

            this._context.SaveChanges();

        }
        catch (Exception exception)
        {
            throw exception;
        }

    }

    public USERPERMISSION Add(USERPERMISSION entity)
    {
        _context.USERPERMISSION.Add(entity);
        _context.SaveChanges();
        return entity;
    }

}

我有一个名为用户权限的类。它与另一个名为USER和PAGE的类有两个外键关系。下面是USERPERMISSION类的内容:

[Table("USERPERMISSION")]
public class USERPERMISSION
{

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }
    [ForeignKey("USER")]
    public int USERID { get; set; }
    [ForeignKey("PAGE")]
    public int PAGEID { get; set; }
    public int? ADD { get; set; }
    public int? EDIT { get; set; }
    public int? DELETE { get; set; }
    public int? READ { get; set; }
    public int? LIST { get; set; }
    public int? REPORT { get; set; }
    public int? PUBLISH { get; set; }
    public int? CONFIRM { get; set; }
    public int ACTIVE { get; set; }
    [StringLength(30)]
    public string CODE { get; set; }

    public virtual USER USER { get; set; }
    public virtual PAGE PAGE { get; set; }

}

为了测试 EfUserPermissionRepository 中定义的 Add 方法,我设计了一个测试代码。我获取用户1的所有USERPERMISSION并将其复制给用户2。目前,用户1有26个用户权限,而用户2没有任何USERPERMISSION。我的意图是将用户1的所有USERPERMISSION列表复制到用户2,并将它们保存到数据库中。下面是测试代码:

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PROJECT.Tests.Soyut;
using PROJECT.Entity.Models;
using System.Collections.Generic;
using System.Linq;

namespace PROJECT.Tests
{
[TestClass]
public class UserPermissionManagerTest : TestBase
{

    private int UserId1 { get; set; }

    private USER User2 { get; set; }
    
    private List<USERPERMISSION> UserPermissionList1 { get; set; }

    /// <summary>
    /// The procedure where the <code>Add</code> procedure was tested against user 2.        
    /// 
    /// It is hoped that it will be successful.
    /// </summary>
    [TestMethod]
    public void USERPERMISSIONAdd_001()
    {

        //’UserPermissionManageri’ is a Business layer component that emerges from TestBase.
        List<USERPERMISSION> list = UserPermissionManageri.Add(UserPermissionList1);
        
        Assert.IsNotNull(list);

        Assert.AreEqual(true, list.Any());

    }

    [TestInitialize]
    public void TestClassInitialize()
    {
        UserId1 = 1;                       

        //’UserManageri’ is a Business layer component that emerges from TestBase.
        User2 = UserManageri.Get(2);

        Assert.IsNotNull(User2);
        
        //Creates a new list by getting all user permission list of user 1 to user 2.
        UserPermissionList1 = this.CopyUserPermissionList(UserId1, User2);

        Assert.IsNotNull(UserPermissionList1);

        Assert.AreEqual(true, UserPermissionList1.Any());

    }

    private List<USERPERMISSION> CopyUserPermissionList(int sourceUserId, USER targetUserToCopy)
    {

        //getting all user permission list of the sourceUserId. 
        List<USERPERMISSION> list = UserPermissionManageri.List(p => p.USERID == sourceUserId);

        //ensure that the list is not null.
        Assert.IsNotNull(list);

        //ensure that the list has a value. 
        Assert.AreEqual(true, list.Any());

        List<USERPERMISSION> copyList = new List<USERPERMISSION>();

        //copying the list to the copylist 
        foreach (USERPERMISSION value in list)
        {
            if (value == null)
                continue;

            copyList.Add(new USERPERMISSION()
            {
                USERID = value.USERID,
                PAGEID = value.PAGEID,
                ADD = value.ADD,
                EDIT = value.EDIT,
                DELETE = value.DELETE,
                READ = value.READ,
                LIST = value.LIST,
                REPORT = value.REPORT,
                PUBLISH = value.PUBLISH,
                CONFIRM = value.CONFIRM,
                ACTIVE = value.ACTIVE,
                CODE = value.CODE,
                USER = value.USER,
                PAGE = value.PAGE,
                ID = 0
            });

        }

        //assigning targetUserToCopy to all elements of copyList 
        foreach (USERPERMISSION permission in copyList)
        {
            if (permission == null)
                continue;

            permission.USER = targetUserToCopy;
            permission.USERID = targetUserToCopy.ID; 
        }

        //returning the copylist.
        return copyList;

    }

   
}
}

USERPERMISSIONAdd_001运行成功,即我运行时测试函数为绿色;但是,它不会对数据库进行任何更改。我哪里错了?先谢了。

qnyhuwrf

qnyhuwrf1#

正如Panagiotis Kanavos所指出的,我从隔离问题开始。我丢弃了test UserPermissionManagerTest 中的 UserPermissionManageri,并在 UserPermissionManagerTest 中创建了一个新的 DbContext。测试类看起来像这样:

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PROJECT.Tests.Soyut;
using PROJECT.Entity.Models;
using System.Collections.Generic;
using System.Linq;
using PROJECT.Dal.Concrete.EntityFramework;

namespace PROJECT.Tests.Concrete.BusinessLayer
{
  [TestClass]
  public class UserPermissionManagerTest : TestBase
  {

    private int UserId1 { get; set; }

    private USER User2 { get; set; }
    
    private List<USERPERMISSION> UserPermissionList1 { get; set; }
    
    private static EfDbContext EfDbContexti { get; set; }

    /// <summary>
    /// The procedure where the <code>Add</code> procedure was tested against user 1665.        
    /// 
    /// It is hoped that it will be successful.
    /// </summary>
    [TestMethod]
    public void USERPERMISSIONAdd_001()
    {

        IEnumerable<USERPERMISSION> list = EfDbContexti.USERPERMISSION.AddRange(UserPermissionList1);

        EfDbContexti.SaveChanges();

        Assert.IsNotNull(list);

        Assert.AreEqual(true, list.Any());

    }

    [TestInitialize]
    public void TestClassInitialize()
    { 

        UserId1 = 17;

        EfDbContexti = new EfDbContext();

        User2 = EfDbContexti.USER.FirstOrDefault(p => p.ID == 1665);
        
        //User2 = UserManageri.Get(1665);

        Assert.IsNotNull(User2);
        
        //Creates a new list by getting all user permission list of user 17 to user 1665
        UserPermissionList1 = this.CopyUserPermissionList(UserId1, User2);

        Assert.IsNotNull(UserPermissionList1);

        Assert.AreEqual(true, UserPermissionList1.Any());

    }
    
    [ClassCleanup]
    public static void TestClassCleanup()
    {

        if (EfDbContexti != null)
        {
            EfDbContexti.SaveChanges();
            EfDbContexti.Dispose();
            EfDbContexti = null;
        }
    }

    private List<USERPERMISSION> CopyUserPermissionList(int sourceUserId, USER targetUserToCopy)
    {

        //getting all user permission list of the sourceUserId. 
        
        IQueryable< USERPERMISSION> iqueryable =  EfDbContexti.USERPERMISSION.Where(p => p.USERID == sourceUserId);

        Assert.IsNotNull(iqueryable);

        List<USERPERMISSION> list = iqueryable.ToList();

        //ensure that list is not null.
        Assert.IsNotNull(list);

        //ensure that list has a value. 
        Assert.AreEqual(true, list.Any());

        List<USERPERMISSION> copyList = new List<USERPERMISSION>();

        //copying the list to copylist 
        foreach (USERPERMISSION value in list)
        {
            if (value == null)
                continue;

            copyList.Add(new USERPERMISSION()
            {
                USERID = value.USERID,
                PAGEID = value.PAGEID,
                ADD = value.ADD,
                EDIT = value.EDIT,
                DELETE = value.DELETE,
                READ = value.READ,
                LIST = value.LIST,
                REPORT = value.REPORT,
                PUBLISH = value.PUBLISH,
                CONFIRM = value.CONFIRM,
                ACTIVE = value.ACTIVE,
                CODE = value.CODE,
                USER = value.USER,
                PAGE = value.PAGE,
                ID = 0
            });

        }

        //assigning targetUserToCopy to all elements of copyList 
        foreach (USERPERMISSION permission in copyList)
        {
            if (permission == null)
                continue;

            permission.USER = targetUserToCopy;
            permission.USERID = targetUserToCopy.ID; 
        }

        //returning the copylist.
        return copyList;

    }

   
}

}
由于 TestBase 有另一个独立的 DbContext 变量,这种情况会导致以下异常:
Entity对象不能被多个IectyChangeTracker示例引用。同时在Entity Framework中为实体添加相关对象。
当我删除 UserPermissionManagerTestTestBase 之间的继承时,问题消失了,相关记录成功保存到数据库中。

相关问题