簡體   English   中英

實體框架核心 HasOne 和 WithMany 不存在

[英]Entity Framework Core HasOne and WithMany doesn’t exist

為什么我在modelBiulder.Entity<T>方法中沒有HasOne()WithMany()參數?

要在 Entity Framework Core 中使用 Fluent API 配置關系,首先要識別構成關系的導航屬性。 HasOneHasMany標識您開始配置的實體類型的導航屬性。 然后,您將調用鏈接到WithOneWithMany以識別反向導航。 HasOne/WithOne用於參考導航屬性, HasMany/WithMany用於集合導航屬性。

請參閱帶有示例的 Microsoft 文檔。

例子:

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public List<Post> Posts { get; set; }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public Blog Blog { get; set; }
}

class ApplicatioinDbContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Post>()
            .HasOne(p => p.Blog)
            .WithMany(b => b.Posts);
    }
}

我有,但它仍然向我顯示警告

public class CarEquipment
{

    public int CarId { get; set; }
    public int EquipmentId { get; set; }

    public Car Car { get; set; }
    public Equipment Equipment { get; set; }
}

public class Equipment
{
    public int EquipmentId { get; set; }
    public IEnumerable<string> Item { get; set; }
    public List<CarEquipment> CarEquipments { get; set; }
}
public class
{
    public int CarId { get; set; }
    public string Brand { get; set; }
    public string Model { get; set; }
    public int Price { get; set; }

    public List<CarEquipment> CarEquipments { get; set; }
}

public DbSet<Car> Cars { get; set; }
    public DbSet<Equipment> Equipments { get; set; }
    public DbSet<CarEquipment> CarEquipments { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Car>().HasKey(x => x.CarId);
        modelBuilder.Entity<CarEquipment>().HasKey(x => new { x.CarId, x.EquipmentId });
        modelBuilder.Entity<Equipment>().HasKey(x => x.EquipmentId);
        modelBuilder.Entity<CarEquipment>().HasOne(x => x.Equipment).WithMany(x => x.CarEquipments);
        modelBuilder.Entity<CarEquipment>().HasOne(x => x.Car).WithMany(x => x.CarEquipments);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM