我正试着把数据输入我的数据库。我有Photos
和AppUser
两节课。它们具有ICollection<Photo> Photos
属性的一对多关系,这意味着每个用户可以拥有多个图像。AppUser
类:
public class AppUser
{
public int Id { get; set; }
public string UserName { get; set; }
public byte[] PasswordHash { get; set; }
public byte[] PasswordSalt { get; set; }
public DateTime DateOfBirth { get; set; }
public string KnownAs { get; set; }
public DateTime Created { get; set; } = DateTime.Now;
public DateTime LastSeen { get; set; } = DateTime.Now;
public string Gender { get; set; }
public string Introduction { get; set; }
public string LookingFor { get; set; }
public string Interests { get; set; }
public string City { get; set; }
public string Country { get; set; }
public ICollection<Photo> Photos { get; set; }
}
Photo
类:
namespace API.Entity
{
[Table("Photos")]
public class Photo
{
public int Id { get; set; }
public string UrL { get; set; }
public bool IsMain { get; set; }
public string PublicId { get; set; }
public AppUser AppUser { get; set; }
public int AppUserId { get; set; }
}
}
Seed
类:
public class Seed
{
public static async Task SeedUsers(DataContext context)
{
if (await context.Users.AnyAsync()) return;
var userData = await System.IO.File.ReadAllTextAsync("Data/UserSeedData.json");
var users = JsonSerializer.Deserialize<List<AppUser>>(userData);
if (users == null) return;
foreach (var user in users)
{
using var hmac = new HMACSHA512();
user.UserName = user.UserName.ToLower();
user.PasswordSalt = hmac.Key;
user.PasswordHash = hmac.ComputeHash(Encoding.UTF8.GetBytes("pa$$w0rd"));
await context.Users.AddAsync(user);
}
await context.SaveChangesAsync();
}
}
生成种子数据的JSON文件(我有很多,这是其中之一):
[
{
"UserName": "Sandy",
"Gender": "female",
"DateOfBirth": "1978-02-23",
"KnownAs": "Sandy",
"Created": "2019-07-28",
"LastActive": "2020-05-24",
"Introduction": "Cupidatat do nostrud et culpa commodo enim minim quis.
"Interests": "Esse sunt sit fugiat tempor voluptate cillum mollit aliquip irure ipsum mollit quis",
"City": "Moscow",
"Country": "Denmark",
"Photos": [
{
"Url": "https://randomuser.me/api/portraits/women/42.jpg",
"IsMain": true
}
]
}
]
Photo
表中的URL设置为空。尽管设置了“IsMain”属性,但设置了它的值并且运行良好。我尝试删除迁移并重新开始,但仍然为空。我想不通了。
1条答案
按热度按时间xkftehaa1#
URL的实体名称和JSON对象名称不匹配。
在您的json文件中,对象名称是:
Url
但在您的实体类中是:
UrL
此外,使用List Insted of ICollect。
AppUser类:
图片类:
JSON文件: