.net core add-migration requires a primary key to be defined

崔单弓
2023-12-01

在新建更新Entity 时, 使用了

// 声明Entity
public class Factory : AuditedAggregateRoot<Guid>
{
    public string Address { get; set; }
    
	public DeviceRefarance Refance
	{
			get; set; 
	}
}

public class DeviceReferance
{
		public string DeviceName
		{
				get; set;
		}
		
		public string DeviceId
		{
				get; set;
		}
}

此时去Migration 中去执行
Add-migration ‘init’ 时会发生以下提示
The entity type ‘DeviceReferance’ requires a primary key to be defined. If you intended to use a keyless entity type, call ‘HasNoKey’ in ‘OnModelCreating’. For more information on keyless entity types, see: https://go.microsoft.com/fwlink/?linkid=2141943.

给出的提示是 定义无键实体类型,

// 使用批注[Keyless]
[Keyless]
public class Factory 
{
    public string Address { get; set; }
    
	public DeviceRefarance Refance
	{
			get; set; 
	}
}

//定义无键实体类型
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Factory >()
        .HasNoKey();
}

本文定义的DeviceReferance仅是一个数据类型而不是实体,所以这个不是想要的答案

使用EF,在ORM内已经定义好了相关的字段和数据库的映射关系。但是要记得为在数据库中没有的字段设置[NoMapped]这个不需要映射的属性。可以通过添加批注[NotMapped]来解决

// [NotMapped]
public class Factory 
{
    public string Address { get; set; }
    [NotMapped]
	public DeviceRefarance Refance
	{
			get; set; 
	}
}

 类似资料:

相关阅读

相关文章

相关问答