简体   繁体   English

从表中获取数据时未设置实体框架对象引用

[英]Entity Framework object reference not set when getting data from table

command = "INSERT INTO clients VALUES(" + NameTB.Text +")";
objCtx.SaveChanges();

List<Client> clients = new List<Client>();
clients = objCtx.ExecuteStoreQuery<Client>("Select * from clients").ToList();

string x = "";
for (int i = 0; i < clients.Count; i++)
     x += clients[i].Name.ToString();//exception here

MessageBox.Show(x);

I just start to work with EF and have no idea how to fix this; 我刚开始使用EF,却不知道如何解决这个问题。 I took the code from here 我从这里取了代码

Sounds like the Name property is null in the Client data that is returned. 听起来好像Name属性在返回的Client数据中为null。

Either have a constraint in the database that this field is required or add a null check: 在数据库中有此字段为必填项的约束或添加空检查:

string x = "";
for (int i = 0; i < clients.Count; i++) {
     if (!String.IsNullOrEmpty(clients[i].Name)) {
          x += clients[i].Name.ToString();
     }
}

Also, if you're going to work with many clients and your string is going to get big I suggest you take a look at StringBuilder . 另外,如果您要与许多客户端一起使用,并且您的字符串将变大,建议您看一下StringBuilder

暂无
暂无

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

相关问题 Entity Framework Core 未从参考表中加载相关数据 - Entity Framework Core not loading related data from reference table Object 引用未设置为 object 的实例。 在 datagridview 实体框架中使用 LinQ 添加两个表 - Object reference not set to an instance of an object. Adding Two Table using LinQ in datagridview Entity Framework 从二级表(实体框架)获取数据 - Getting data from a second level table (entity framework) 添加具有Entity Framework多对多关系的项目时,“对象引用未设置为对象错误的实例” - “Object reference not set to an instance of an object error” when adding an item with Entity Framework Many-To-Many relationship Mocking Entity Framework为我提供了未设置为对象实例的Object引用 - Mocking Entity Framework gives me Object reference not set to an instance of an object MySql 和实体框架导致“未将对象引用设置为对象的实例”。 - MySql & Entity Framework causing “Object reference not set to an instance of an object.” Entity Framework Power Tools:错误“对象引用未设置为对象的实例” - Entity Framework Power Tools: error “Object Reference not set to an instance of an object” 带有 DBQuery 的实体框架核心 2 - 获取 Object 引用未设置为 object 的实例 - Entity Framework Core 2 with DBQuery - Get Object reference not set to an instance of an object 从存储库获取实体 object 时如何设置它的 ID - How to set Id of Entity object when getting it from Repository 从Entity Framework中的不同表格获取平均值 - Getting averages from different table in Entity Framework
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM