繁体   English   中英

Entity Framework Core - Fluent API 未配置模型

[英]Entity Framework Core - Fluent API not configuring model

我一直在尝试使用 fluent API 来配置我的模型。 我找不到问题所在。 它似乎没有强制执行任何约束,但我可以看到创建模型时运行的代码。 文档说 Fluent API 将覆盖任何以前的注释,即优先。

当我在模型中使用数据注释时,一切正常。 这是一个有效的代码示例(在模型中 - 数据注释)与一个无效的代码示例(在上下文中 - OnModelCreating)。

//In Model
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;

namespace ParkingPermitData.Models
{

    public class PermitPurchase
    {
        public int PermitPurchaseId { get; set; }
        [Required]
        public string ParkingPermitNumber { get; set; }
        public string PurchaserName { get; set; }
    }
}

//In Context
using Microsoft.EntityFrameworkCore;
using ParkingPermitData.Models;
namespace ParkingPermitData.Data
{
    public class ParkingPermitContext : DbContext
    {
        public ParkingPermitContext(DbContextOptions<ParkingPermitContext> options) : base(options)
        {
        }

        public DbSet<PermitPurchase> PermitPurchases { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<PermitPurchase>().ToTable("PermitPurchase");

            modelBuilder.Entity<PermitPurchase>()
                .Property(b => b.ParkingPermitNumber)
                .IsRequired();

        }
    }
}

我已经尝试将 OnModelCreating 中的代码作为单个语句以及我在示例中发现的许多其他变体。 我试图设置一些比这更复杂的关系和注释,但想知道为什么它们不起作用,然后尝试了这个非常简单的案例。 这非常令人沮丧,我将不胜感激。

需要注意的一件事是我在早期开发中将 InMemoryDatabase 用于 DBContext。

//Startup
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ParkingPermitContext>(opt =>
                            opt.UseInMemoryDatabase("ParkingPermitPurchases"));
    services.AddControllers();
}

非常感谢,保罗

在内存中,数据库无视 db 约束,因为它不是关系数据库。 特别是

InMemory 将允许您保存在关系数据库中违反参照完整性约束的数据。

查看文档

有关支持的内容的更多信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM