asp.net – 在使用“EF-Code First”时如何定义Keys?

使用“EF-Code First”时,我得到一个ModelValidationException(在底部).它希望我定义一个Key,但我不确定它究竟意味着什么……

public class Unit
{
    Guid id;
    String public_id;
    String name;        
    bool deleted;
}

public class MyDataContext : DbContext
{
    public DbSet<Unit> Units { get; set; }

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

[TestFixture]
public class DataTests
{
    [Test]
    public void test()
    {
        MyDataContext database = new MyDataContext();
        var o = database.Units;


        Console.WriteLine(o.Count()); // This line throws!
        Assert.IsTrue(true);
    }
}

System.Data.Entity.ModelConfiguration.ModelValidationException : One or more validation errors were detected during model generation:

System.Data.Edm.EdmEntityType: : EntityType ‘Unit’ has no key defined. Define the key for this EntityType.

System.Data.Edm.EdmEntitySet: EntityType: The EntitySet Units is based on type Unit that has no keys defined.

解决方法

对于希望EF为其创建数据库字段的所有字段,您需要使用属性,而不是私有局部变量.

Public Guid Id {get;组;}

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....