在使用C# efcore时,发现一个关于对象导航属性神奇的现象

如果你在导航属性默认了一个新的对象,那么在efcore生成的SqL中生成一条新的插入数据到导航属性的表中

举例:

 

public class Asset 
{ 
  public int AssetId {get;set;}
public int DeptId {get;set;} public virtual Department? Department { get; set; } = new Department(); }

 

在配置好Fluent API后

public class AssetTypeConfig: IEntityTypeConfiguration<Asset>
    {
        public void Configure(EntityTypeBuilder<Asset> builder)
        {
            builder.HasKey(asset=>asset.AssetId);

            builder
                .HasOne(asset => asset.Department)
                .WithMany()
                .HasForeignKey(asset => asset.DeptId);
        }
    }

 

如果你是要修改Asset这个类的数据,然后你会神奇发现

在Department数据表里面会自动的创建一条空的Department数据,将起修改为:

public virtual Department? Department { get; set; }

这样再修改Asset就不会自动插入一条空的Department数据了。

估计这是Efcore的一种机制吧。

posted @ 2023-01-17 17:22  飞雪连天e^πi+1=0  阅读(125)  评论(0)    收藏  举报