简体   繁体   中英

How to add object to database (EntityFramework) C#

I'm a beginner in .net and last time I tried to learn EntityFranework . I made simple project and had an issue:

Error CS1503 Argument 1: cannot convert from 'ABC.Customer' to '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 .

If EntityData has a definition for 'Order' and you're trying to save it to that table you can try this:

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. When you try to save it, Entity Framework sees this and rejects it, even though Customer may have the same properties as 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:

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. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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