简体   繁体   English

如何将对象添加到数据库(EntityFramework)C#

[英]How to add object to database (EntityFramework) C#

I'm a beginner in .net and last time I tried to learn EntityFranework .我是 .net 的初学者,上次我尝试学习EntityFranework I made simple project and had an issue:我做了一个简单的项目,但遇到了一个问题:

Error CS1503 Argument 1: cannot convert from 'ABC.Customer' to 'ABC.Order'错误 CS1503 参数 1:无法从“ABC.Customer”转换为“ABC.Order”

I was trying to solve it on my own but w/o success, I'll appricaite for all help.我试图自己解决它,但没有成功,我会寻求所有帮助。

Code:代码:

EntityData db = new EntityData();
var _Order = new Customer();

var newOrder = db.Orders.ToList();

_Order.number = int.Parse(TextBox1.Text);

newOrder.Add(_Order); // _Order is wrong
db.SaveChanges();

My customer class have only one property:我的客户类只有一个属性:

public int number { get; set; }

My database has only one table: Order with one property: number .我的数据库只有一张表: Order with a property: number

If EntityData has a definition for 'Order' and you're trying to save it to that table you can try this:如果 EntityData 有“订单”的定义,并且您尝试将其保存到该表中,则可以尝试以下操作:

EntityData db = new EntityData();
var _Order = new Order();

_Order.number = int.Parse(TextBox1.Text);

db.Order.Add(_Order); // _Order is wrong
db.SaveChanges();

When you run this code, it sees _Order as an instance of Customer.当您运行此代码时,它会将 _Order 视为 Customer 的一个实例。 When you try to save it, Entity Framework sees this and rejects it, even though Customer may have the same properties as Order.当您尝试保存它时,实体框架会看到并拒绝它,即使 Customer 可能具有与 Order 相同的属性。

You will need to do something like this to get Entity Framework to not reject your action.您需要执行类似的操作才能让实体框架不拒绝您的操作。

db.Orders.Add(new Order{Number = _Order.number});

Many thanks for all hints.非常感谢所有提示。 I followed for one which was the most popular - change below:我关注了最受欢迎的一个 - 更改如下:

var _Order = new Customer();

on

var _Order = new Order();

Back to Customer class - it contains only one property:回到 Customer 类——它只包含一个属性:

public int number { get; set; }

The reason why I prepared separate class named Customer is in fact, that on one tutorial I saw this kind of solution.我准备单独的名为Customer类的原因实际上是在一个教程中我看到了这种解决方案。 To be honest, I had to make a mistake with my though process and now almost everything is working (data is not saved).老实说,我不得不在我的过程中犯了一个错误,现在几乎一切都在工作(数据没有保存)。

Whole app I made only for my learn and I used incorrect naming condiiton such as Customer .我制作的整个应用程序只是为了我的学习,我使用了不正确的命名条件,例如Customer

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

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