[英]EF Core 5 - Set custom property value in custom join table
Based on examples, I created the following custom join table (using EF Core 5), since I needed an extra property in my custom join table:根据示例,我创建了以下自定义连接表(使用 EF Core 5),因为我的自定义连接表中需要一个额外的属性:
modelBuilder.Entity<Property>(property =>
{
property
.HasMany(_ => _.Addresses)
.WithMany(_ => _.Properties)
.UsingEntity<PropertyAddress>(
_ => _.HasOne(_ => _.Address).WithMany().HasForeignKey(_ => _.AddressId),
_ => _.HasOne(_ => _.Property).WithMany().HasForeignKey(_ => _.PropertyId));
});
public class PropertyAddress
{
public string PropertyId { get; set; }
public string AddressId { get; set; }
public int SequenceNumber { get; set; }
public Property Property { get; set; }
public Address Address { get; set; }
}
public class Property
{
public ICollection<Address> Addresses { get; set; }
}
public class Address
{
public ICollection<Property> Properties { get; set; }
}
The custom join table PropertyAddress
is working as expected, however: How can I (programmatically) set the values for the custom property PropertyAddress.SequenceNumber
before saving/updating records?自定义连接表
PropertyAddress
正在按预期工作,但是:如何在保存/更新记录之前(以编程方式)设置自定义属性PropertyAddress.SequenceNumber
的值? (Because the whole joining mechanism is (now) still being handled 'behind the scene' by EF Core.) (因为整个加入机制(现在)仍然由 EF Core 在“幕后”处理。)
1-First, you should have public DbSet PropertyAddress{ get; 1-首先,你应该有 public DbSet PropertyAddress{ get; set;
放; } in your DBContext ,then use it to insert your object.
在您的 DBContext 中,然后使用它来插入您的对象。 example:
例子:
1-Entity 1-实体
public class GroupMember
{
public int GroupMemberId { get; set; }
[Required]
public int UserId { get; set; }
[Required]
public int GroupId { get; set; }
[Required]
public DateTime JoinDate { get; set; }
[Required]
public int RoleTypeGroupId { get; set; }
//Navigation
public User User { get; set; }
public Group Group { get; set; }
public RoleTypeGroup RoleType { get; set; }
}
2-DbContext 2-DbContext
public class AppDataContext : DbContext
{
//Code
public DbSet<GroupMember> GroupMembers { get; set; }
}
3-you need create object of PropertyAddress and set his value as you want. 3-您需要创建 PropertyAddress 对象并根据需要设置其值。
4- use EF to insert the object or update it 4-使用EF插入对象或更新它
unitOfWork.GroupMemberRepository.Add(groupMember);
unitOfWork.SaveChanges();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.