小编Vin*_*kar的帖子

如何模拟实体框架的FromSqlRaw方法?

我正在编写单元测试,需要模拟实体框架的 .FromSqlRaw 方法。当该方法在被测类中执行时,会抛出以下异常:

System.InvalidOperationException:类型“Microsoft.EntityFrameworkCore.RelationalQueryableExtensions”上没有与指定参数匹配的方法“FromSqlOnQueryable”。

以下是被测试的类:

public class PowerConsumptionRepository : IPowerConsumptionRepository
    {
        private readonly IDatabaseContext _databaseContext;
        private readonly IDateTimeHelper _dateTimeHelper;

        public PowerConsumptionRepository(IDatabaseContext databaseContext, IDateTimeHelper dateTimeHelper)
        {
            _databaseContext = databaseContext;
            _dateTimeHelper = dateTimeHelper;
        }
        public List<IntervalCategoryConsumptionModel> GetCurrentPowerConsumption(string siteId)
        {
            var currentDate = _dateTimeHelper
                .ConvertUtcToLocalDateTime(DateTime.UtcNow, ApplicationConstants.LocalTimeZone)
                .ToString("yyyy-MM-dd");
            var currentDateParameter = new SqlParameter("currentDate", currentDate);
            var measurements = _databaseContext.IntervalPowerConsumptions
                .FromSqlRaw(SqlQuery.CurrentIntervalPowerConsumption, currentDateParameter)
                .AsNoTracking()
                .ToList();
            return measurements;
        }
    }
Run Code Online (Sandbox Code Playgroud)

单元测试:


    public class PowerConsumptionRepositoryTests
    {
        [Fact]
        public void TestTest()
        {
            var data = new List<IntervalCategoryConsumptionModel>
            {
                new IntervalCategoryConsumptionModel …
Run Code Online (Sandbox Code Playgroud)

c# xunit nsubstitute entity-framework-core asp.net-core

5
推荐指数
2
解决办法
8175
查看次数

Spring Boot JPA Lazy Fetch 不起作用

我有以下两个域对象 Suggestion 和 UserProfile

它们以一对多的关系相互映射。当我使用 Spring Data JPA 获取所有建议时,我会使用每个建议对象获得相应的用户对象。即使我设置fetchFetchType.Lazy. 以下是我的代码:

建议.java

@Entity
@Table(name="suggestion")
@JsonIgnoreProperties({"suggestionLikes"})
public class Suggestion {

public Suggestion() {
    // TODO Auto-generated constructor stub
}

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="suggestion_id")
private Integer suggestionId;

@Column(name="description")
private String description;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="suggestion_by")
private UserProfile user;

//getters and setters
}
Run Code Online (Sandbox Code Playgroud)

用户配置文件

@Entity
@Table(name = "user_master")
@JsonIgnoreProperties({"suggestions", "suggestionLikes"})
public class UserProfile implements Serializable {

/**
 * 
 */
private static final long serialVersionUID = 7400472171878370L;


public UserProfile() {

}


@Id …
Run Code Online (Sandbox Code Playgroud)

java spring hibernate spring-data-jpa spring-boot

4
推荐指数
2
解决办法
7351
查看次数