我正在编写一个应用程序,它从外部 API 提取数据并使用实体框架将其存储到我的 SQL Server 数据库中。我每天从这个 API 中提取数据,因此如果一行已经存在,记录将被更新,否则将创建一条新记录。这是通过检查 Id 来完成的。
现在我遇到的问题是我只想 EF 更新BranchId和CustomerNameTopdesk。该CustomerNamePRTG值是我自己手动添加到数据库中的。因此,现在当记录更新时,它会设置回 NULL,并且我手动插入的值将丢失。
更新前
更新后
来自 API 的数据从 JSON 反序列化并data作为 a 存储在变量中List<Customers>.。我使用以下代码来检查 Id 记录是否已存在并更新它,否则创建一个新记录。正如您所看到的,它当前正在更新整个Customer记录,包括CustomerNamePRTGNULL 的记录
string apiResponse = await response.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<List<Customers>>(apiResponse);
foreach (Customers customer in data)
{
if (db.Customers.Any(x => x.BranchId == customer.BranchId))
{
db.Customers.Update(customer);
}
else
{
db.Customers.Add(customer);
}
db.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)
模型
public class Customers
{
[Key]
[JsonProperty("id")]
public string BranchId …Run Code Online (Sandbox Code Playgroud) 我一直在尝试测试 CrudRepository 中的 findById() 方法。这个方法返回一个Optional,我不知道如何返回它,现在它给了我一个NullPointerException。
我的测试代码如下所示:
@RunWith(MockitoJUnitRunner.class)
public class DishServiceMockTest {
private static final String DISH_NAME = "Kaas";
private static final String DISH_TYPE = "Voorgerecht";
private static final Long DISH_ID = 23L;
//Mock the service dependencies(=DishServiceImpl is dependent on dishRepo)
@Mock
DishRepository dishRepository;
//Mock the service which is to be tested (Can't be a interface)
@InjectMocks
DishServiceImpl dishService;
@Test
public void findById(){
//Arange
Dish dish = createDish(DISH_ID, DISH_NAME, DISH_TYPE);
Mockito.when(dishRepository.findById(DISH_ID)).thenReturn(Optional.of(dish));
assertThat(dishService.findById(DISH_ID)).isEqualTo(dish);
}
Run Code Online (Sandbox Code Playgroud)
运行测试给出了 2 个错误,其中之一是 NullPointerException,第二个是: …
我想编写一个 FindAll() 方法,该方法返回所有 Student 对象的列表。但是 CRUDRepository 只有 Iterable<> findAll()。
目标是将所有学生放在一个列表中并将其传递给 API 控制器,以便我可以通过 http GET 获取所有学生。
将此方法转换为 List<> FindAll() 的最佳方法是什么
在我当前的代码中,StudentService 中的 findAll 方法给了我找到的不兼容类型:Iterable。必需:列表错误。
服务
@Service
@RequiredArgsConstructor
public class StudentServiceImpl implements StudentService {
@Autowired
private final StudentRepository studentRepository;
//Incompatible types found: Iterable. Required: List
public List<Student> findAll() {
return studentRepository.findAll();
}
}
Run Code Online (Sandbox Code Playgroud)
API控制器
@RestController
@RequestMapping("/api/v1/students")
public class StudentAPIController {
private final StudentRepository studentRepository;
public StudentAPIController(StudentRepository studentRepository) {
this.studentRepository = studentRepository;
}
@GetMapping
public ResponseEntity<List<Student>> findAll() {
return ResponseEntity.ok(StudentServiceImpl.findAll());
}
}
Run Code Online (Sandbox Code Playgroud)
学生资料库 …
我有一个视图,它显示了存储在我的数据库中的设备表,该数据库是使用 Code-First 和 Entity Framework Core 创建的。现在我的目标是同时更新多行的 EnableAlertsUpload 布尔值。如下图所示。
现在,当我运行代码并按下更新按钮时,页面将刷新而不更新 EnableAlertsUpload 布尔值。对此的任何帮助将不胜感激,大多数解释只告诉 ho 按 ID 更新单个值,而不是同时更新多行。
我的代码如下所示:
控制器
public async Task<IActionResult> EditList()
{
var devices = db.Devices;
return View(devices);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EditList(int id, [Bind("EnableAlertsUpload")] Devices[] devices)
{
if (ModelState.IsValid)
{
try
{
foreach (Devices dev in devices)
{
db.Update(dev);
}
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
return NotFound();
}
return RedirectToAction(nameof(IndexV2));
}
return View(devices);
}
Run Code Online (Sandbox Code Playgroud)
编辑列表视图
@model IEnumerable<FrontlineAI.Models.Devices>
<h1>Devices</h1>
<form asp-action="EditList">
<table class="table">
<thead>
<tr>
<th> …Run Code Online (Sandbox Code Playgroud) 我试图将每个用户的角色包含在列表中,如下图所示。在 Index 方法中,我想将用户加入角色并将其发送到视图。但由于某种原因user.Roles没有被认可。所以看起来导航属性是缺乏的。我在下面添加了屏幕截图以更清楚地说明我的问题。我一直在遵循几个指南,它们似乎都使用起来user.Roles没有任何问题。
该代码对我来说似乎是正确的,我在这里缺少什么吗?
账户控制器
private AppIdentityDbContext context;
public AccountController(AppIdentityDbContext _context)
{
context = _context;
}
public IActionResult Index()
{
var usersWithRoles = (from user in context.Users
select new
{
Username = user.UserName,
Email = user.Email,
RoleNames = (from userRole in user.Roles
join role in context.Roles on userRole.RoleId
equals role.Id
select role.Name).ToList()
}).ToList().Select(p => new UsersViewModel()
{
Username = p.Username,
Email = p.Email,
Role = string.Join(",", p.RoleNames)
});
return View(usersWithRoles);
}
Run Code Online (Sandbox Code Playgroud)
用户视图模型
public class UsersViewModel
{ …Run Code Online (Sandbox Code Playgroud) asp.net-core ×3
c# ×3
java ×2
spring-boot ×2
spring-mvc ×2
asp.net-mvc ×1
junit ×1
mockito ×1
razor ×1
spring ×1