简体   繁体   English

实体框架核心 - ForeingKey显示空值

[英]Entity Framework Core - ForeingKey show null values

I'm developing a Entity Framework with ASP.NET Core and i'm building a database in SQL Express 2017 and a REST API using C#. 我正在使用ASP.NET Core开发实体框架,我正在使用C#在SQL Express 2017和REST API中构建数据库。

I have two models (Usuario and Alimento): This is my Alimento model: 我有两个型号(Usuario和Alimento):这是我的Alimento型号:

public class Alimento{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int codAl { get; set; }

[Required(ErrorMessage = "Se requiere de una denominacion")]
[StringLength(50, MinimumLength = 2)]
public string Descripcion { get; set; }

public string Cantidad { get; set; }

[Required(ErrorMessage = "Calorias es imprescindible")]
[DataType(DataType.Currency)]
[Range(1, 999, ErrorMessage = "El rango debe estar entre 1 y 999")]
public int Calorias { get; set; }
    }

and this is my Usuario model: 这是我的Usuario模型:

public class Usuario{
public int Id { get; set; }
public string email { get; set; }

[Required(ErrorMessage = "Se requiere de una denominacion")]
[StringLength(50, MinimumLength = 2)]
public string nombre { get; set; }

public Alimento alimento { get; set; }
}

When i migrate the solution and update the database, i can see the attribute "alimento" in USUARIO table like "alimentocodAl". 当我迁移解决方案并更新数据库时,我可以在USUARIO表中看到属性“alimento”,如“alimentocodAl”。

I'm trying to modelize "A food(ALIMENTO) has been eaten by an user(USUARIO)" I have a controller that i get all entries from a specific user, but when I use the API, my foreing key in USUARIO table (Usuario foreing key to Alimento by codAl) show null values, for example: 我正在尝试模型化“食物(ALIMENTO)已被用户吃掉(USUARIO)”我有一个控制器,我从特定用户获得所有条目,但是当我使用API​​时,我在USUARIO表中的外出键( Usuario通过codAl显示Alimento的关键字显示空值,例如:

[{"id":1,"email":"mail","nombre":"nombre","alimento":null}, 
{"id":2,"email":"mail","nombre":"nombre","alimento":null}, 
{"id":3,"email":"mail","nombre":"nombre","alimento":null}]

This isn't correct because I have values in this colum inside my table. 这是不正确的,因为我在表格中的这个列中有值。

The code that execute the controller is: 执行控制器的代码是:

public IEnumerable<Usuario> GetInfoUsuario(string email)
{
    var user = ctx.usuarios.ToList().Where(b => b.email == email);
    return user;
}

What i have wrong? 我错了什么?

this is for an REST APi developed with ASP.NET and Entity Framework Core running in Windows 7. 这适用于在Windows 7中运行的ASP.NET和Entity Framework Core开发的REST APi。

您可以尝试将Alimanto包括在内

ctx.usuarios.Include(b => b.alimento)

You are retrieving only Usuario from database. 您只从数据库中检索Usuario If you want to get any additional info you need to use Include . 如果您想获得任何其他信息,您需要使用Include

Instead of line var user = ctx.usuarios.ToList().Where(b => b.email == email); 而不是line var user = ctx.usuarios.ToList().Where(b => b.email == email);

You need to have var user = ctx.usuarios.Where(b => b.email == email).Include(usr => usr.alimento).ToList(); 你需要有var user = ctx.usuarios.Where(b => b.email == email).Include(usr => usr.alimento).ToList();

Ps PS

I moved ToList() as the last operation because it evaluates expression. 我将ToList()移动为最后一个操作,因为它评估表达式。 Now it will filter table before retrieving data instead of downloading all users and filtering afterwards. 现在它将在检索数据之前过滤表,而不是下载所有用户并在之后进行过滤。

Try to map with this example: 尝试使用此示例进行映射:

public class Usuario{
public int Id { get; set; }
public string email { get; set; }

[Required(ErrorMessage = "Se requiere de una denominacion")]
[StringLength(50, MinimumLength = 2)]
public string nombre { get; set; }

[ForeignKey("alimento")]
public int AlimentoId {get; set;}

public virtual Alimento alimento { get; set; }
}


public class Alimento{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int codAl { get; set; }

[Required(ErrorMessage = "Se requiere de una denominacion")]
[StringLength(50, MinimumLength = 2)]
public string Descripcion { get; set; }

public string Cantidad { get; set; }

[Required(ErrorMessage = "Calorias es imprescindible")]
[DataType(DataType.Currency)]
[Range(1, 999, ErrorMessage = "El rango debe estar entre 1 y 999")]
public int Calorias { get; set; }

public virtual ICollection<Usario> Users {get; set;}
    }

Right one to many mapping should be created with code above. 应使用上面的代码创建正确的一对多映射。 Something like this should be received from Usario table. 应该从Usario表中收到这样的东西。

[{"id":1,"email":"mail","nombre":"nombre","AlimentoId":1}] 

Make Foreign Key Field "virtual". 使外键字段“虚拟”。 Change 更改

public Alimento alimento { get; set; }

to the following 以下

public virtual Alimento alimento { get; set; }

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

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