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

15 篇文章 0 订阅
在使用EF Core进行数据库迁移时遇到错误,提示`DeviceReferance`实体需要定义主键。博客指出,虽然`DeviceReferance`被误标记为实体,但实际上它只是一个数据类型。解决方案是通过添加`[NotMapped]`批注排除该类型不映射到数据库,从而避免主键定义问题。
摘要由CSDN通过智能技术生成

在新建更新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; 
	}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值