gpt4 book ai didi

c# - Entity Framework 代码优先映射

转载 作者:太空狗 更新时间:2023-10-29 21:41:42 26 4
gpt4 key购买 nike

我有两个类,Group类与User类(代表用户所属的组)是多对多的关系,然后group类也与用户类(代表所有者)有一对多的关系一组)。

我如何映射它?

public class User
{
public int Id { get; set; }
public string Avatar { get; set; }
public string Name { get; set; }
public string Message { get; set; }

public virtual ICollection<Group> OwnedGroups { get; set; }
public virtual ICollection<Group> Groups { get; set; }
}

public class Group
{
public int Id { get; set; }
public DateTime CreateDate { get; set; }
public DateTime ModifyDate { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public bool System { get; set; }
public int ViewPolicy { get; set; }
public int JoinPolicy { get; set; }
public string Avatar { get; set; }
public int Order { get; set; }
public int GroupType { get; set; }

public virtual User Owner { get; set; }
public virtual ICollection<User> Members { get; set; }
}

提前致谢!

最佳答案

我会使用流畅的 API:

public class Context : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Group> Groups { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);

modelBuilder.Entity<User>()
.HasMany(u => u.Groups)
.WithMany(g => g.Members);

modelBuilder.Entity<User>()
.HasMany(u => u.OwnedGroups)
.WithRequired(g => g.Owner)
.WillCascadeOnDelete(false);
}
}

数据注释也应该是可能的:

public class User
{
...

[InverseProperty("Owner")]
public virtual ICollection<Group> OwnedGroups { get; set; }
[InverseProperty("Members")]
public virtual ICollection<Group> Groups { get; set; }
}

public class Group
{
...

[InverseProperty("OwnedGroups")]
public virtual User Owner { get; set; }
[InverseProperty("Groups")]
public virtual ICollection<User> Members { get; set; }
}

InverseProperty 在关系的两边都不需要,但它的定义更清晰。

关于c# - Entity Framework 代码优先映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5720889/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com