I'm trying to insert some data in my database using Entity Framework model, but for some unknown reasons to me, it does nothing.
Am I missing something here?
using (var context = new DatabaseEntities())
{
var t = new test
{
ID = Guid.NewGuid(),
name = "blah",
};
context.AddTotest(t);
context.SaveChanges();
}
It should be:
context.TableName.Add(TableEntityInstance);
For versions of entity framework before 6, it was:
context.TableName.AddObject(TableEntityInstance);
Where:
TableName: the name of the table in the database.
TableEntityInstance: an instance of the table entity class.
If your table is Orders, then:
Order order = new Order();
context.Orders.Add(order);
For example:
var id = Guid.NewGuid();
// insert
using (var db = new EfContext("name=EfSample"))
{
var customers = db.Set<Customer>();
customers.Add( new Customer { CustomerId = id, Name = "John Doe" } );
db.SaveChanges();
}
Here is an example:
public void UpdatePlayerScreen(byte[] imageBytes, string installationKey)
{
var player = (from p in this.ObjectContext.Players where p.InstallationKey == installationKey select p).FirstOrDefault();
var current = (from d in this.ObjectContext.Screenshots where d.PlayerID == player.ID select d).FirstOrDefault();
if (current != null)
{
current.Screen = imageBytes;
current.Refreshed = DateTime.Now;
this.ObjectContext.SaveChanges();
}
else
{
Screenshot screenshot = new Screenshot();
screenshot.ID = Guid.NewGuid();
screenshot.Interval = 1000;
screenshot.IsTurnedOn = true;
screenshot.PlayerID = player.ID;
screenshot.Refreshed = DateTime.Now;
screenshot.Screen = imageBytes;
this.ObjectContext.Screenshots.Add(screenshot);
this.ObjectContext.SaveChanges();
}
}
var context = new DatabaseEntities();
var t = new test //Make sure you have a table called test in DB
{
ID = Guid.NewGuid(),
name = "blah",
};
context.test.Add(t);
context.SaveChanges();
Should do it
[HttpPost] // it use when you write logic on button click event
public ActionResult DemoInsert(EmployeeModel emp)
{
Employee emptbl = new Employee(); // make object of table
emptbl.EmpName = emp.EmpName;
emptbl.EmpAddress = emp.EmpAddress; // add if any field you want insert
dbc.Employees.Add(emptbl); // pass the table object
dbc.SaveChanges();
return View();
}
Related
I have odd problem. The code below wont save new LookupGroup objects
LookupGroup lookup = null;
using (var db = new WaybackDbContext())
{
lookup = db.LookupGroups.SingleOrDefault(x => x.Name.Equals(lookupName, StringComparison.InvariantCultureIgnoreCase));
if (lookup == null)
{
lookup = new LookupGroup
{
Name = lookupName
};
db.SaveChanges();
}
}
The LookupGroup is initiated but it isn't saved and its id is 0.
What could be stopping it from saving?
Add it to context:
if (lookup == null)
{
lookup = new LookupGroup
{
Name = lookupName
};
db.LookupGroups.Add(lookup);
db.SaveChanges();
}
I have method in controller
It receive data from post request and write to table
Here is code
[ResponseType(typeof(TimeTable))]
public IHttpActionResult PostTimeTable(TimeTable timeTable)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (ModelState.IsValid)
{
DateTime dt = DateTime.Today;
TimeTable c = (from x in db.TimeTables
where x.Company == timeTable.Company && x.INN == timeTable.INN
select x).First();
c.StartPause = timeTable.StartPause;
c.StartDay = timeTable.StartDay;
c.EndPause = timeTable.EndPause;
c.EndDay = timeTable.EndDay;
db.SaveChanges();
}
db.TimeTables.Add(timeTable);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = timeTable.Id }, timeTable);
}
But it works well when record with INN and Company already in db.
But if it not in database I need to create new entry.
How I need to modify this method?
You can use a flag (exisingCompanyFlag) for edit mode or add new mode like this
bool existingCompanyFlag = true;
TimeTable c = (from x in db.TimeTables
where x.Company == timeTable.Company && x.INN == timeTable.INN
select x).FirstOrDefult();
if (c == null)
{
existingCompanyFlag = false;
c = new TimeTable();
}
c.StartPause = timeTable.StartPause;
c.StartDay = timeTable.StartDay;
c.EndPause = timeTable.EndPause;
c.EndDay = timeTable.EndDay;
if (!existingCompanyFlag)
db.TimeTables.Add(c);
You need a separate branch in your code for the insert case.
if (ModelState.IsValid) {
if (addingNewRow) {
TimeTable tt = new TimeTable {
// Populate properties (except identity columns)
};
db.TimeTables.Add(tt);
} else {
// update
}
db.SaveChanges();
}
To link to other entities use one of:
Assign instances:
x.Company = theCompany;
or, assign the instance id
x.CompanyId = companyId;
(#1 is easier if you already have the other entity loaded or are creating it – EF will sort out the ids – while #2 saves loading the whole other entity.)
I have a problem with LINQ query (see comment) there is a First method and it only shows me the first element.
When I write in the console "Sales Representative" it shows me only the first element of it as in
I would like to get all of data about Sales Representative. How can I do it?
public PracownikDane GetPracownik(string imie)
{
PracownikDane pracownikDane = null;
using (NORTHWNDEntities database = new NORTHWNDEntities())
{
//Employee matchingProduct = database.Employees.First(p => p.Title == imie);
var query = from pros in database.Employees
where pros.Title == imie
select pros;
// Here
Employee pp = query.First();
pracownikDane = new PracownikDane();
pracownikDane.Tytul = pp.Title;
pracownikDane.Imie = pp.FirstName;
pracownikDane.Nazwisko = pp.LastName;
pracownikDane.Kraj = pp.Country;
pracownikDane.Miasto = pp.City;
pracownikDane.Adres = pp.Address;
pracownikDane.Telefon = pp.HomePhone;
pracownikDane.WWW = pp.PhotoPath;
}
return pracownikDane;
}
Right now you are just getting the .First() result from the Query collection:
Employee pp = query.First();
If you want to list all employees you need to iterate through the entire collection.
Now, if you want to return all the employee's you should then store each new "pracownikDane" you create in some sort of IEnumerable
public IEnumerable<PracownikDane> GetPracownik(string imie) {
using (NORTHWNDEntities database = new NORTHWNDEntities())
{
var query = from pros in database.Employees
where pros.Title == imie
select pros;
var EmployeeList = new IEnumerable<PracownikDane>();
foreach(var pp in query)
{
EmployeeList.Add(new PracownikDane()
{
Tytul = pp.Title,
Imie = pp.FirstName,
Nazwisko = pp.LastName,
Kraj = pp.Country,
Miasto = pp.City,
Adres = pp.Address,
Telefon = pp.HomePhone,
WWW = pp.PhotoPath
});
}
return EmployeeList;
}
Then, with this returned List you can then do what ever you wanted with them.
I am using following code snippet to set the Invoice ID of Invoices in plugin pre-operation. But I am unable to do so. I want to seek your kind suggestion to set the value.
Update
QueryExpression qe = new QueryExpression
{
EntityName = "invoice",
ColumnSet = new ColumnSet("salesorderid", "invoicenumber"),
Criteria = new FilterExpression
{
Conditions = {
new ConditionExpression("salesorderid",ConditionOperator.Equal,orderId)
}
}
};
EntityCollection ec = service.RetrieveMultiple(qe);
if (ec.Entities.Count == 0)
{
string orderName = generateInvoiceID(service, orderId);
foreach (Entity id in ec.Entities)
{
id.Attributes["invoicenumber"] = Convert.ToInt32(orderName) + 01;
}
}
Looking at the snippet looks like you have the plugin registered on "SalesOrder" entity and you are trying to update invoice entity, so it does not matter if it is a pre-op or a post-op, you would need to explicitly call IOrganizationService.Update
var qe = new QueryExpression
{
EntityName = "invoice",
ColumnSet = new ColumnSet("salesorderid", "invoicenumber"),
Criteria = new FilterExpression
{
Conditions =
{
new ConditionExpression("salesorderid", ConditionOperator.Equal, orderId)
}
}
};
var ec = service.RetrieveMultiple(qe);
var orderName = generateInvoiceID(service, orderId);
foreach (var entity in ec.Entities)
{
var invoice = new Entity("invoice") { Id = entity.Id };
invoice.Attributes.Add("invoicenumber", Convert.ToInt32(orderName) + 01);
service.Update(invoice); //call the update method.
}
Just playing around with entity framework.
Now I have a simple database, containing to Entities
Person (Id, Name)
Profession (Id, Designation)
which has an association on the Id.
I want to give a person a new profession programatically with this code:
using (PersonDataModelContainer dmc = new PersonDataModelContainer())
{
var pers = new Person() { Id = PersonId };
dmc.Person.Attach(pers);
var prof = new Profession() { Id = ProfessionId };
dmc.Profession.Attach(prof);
pers.Professions.Add(req);
var result = dmc.SaveChanges();
return (result > 0);
};
I'm quite new to EF, so it is possibly quite simple.
the effect is: nothing happens and I do not see any
new Association in the associations table.
How can I add a new association from existing entities?
Is there any good documentation on working with that concept?
-edit-
found a copy of the database in the bin\debug folder.
It doesn't contain associations either. but there seems
to be writes to that file each time I fire the update as
in the code above.
I guess you should to use this SQL Compact, Identity Columns and Entity Framework
using (var con = new PersonDataModelContainer())
{
var pers = new Person() { Id = PersonId };
int pId = 0;
if (pers.PersonId > 0)
{
pers = con.Persons.FirstOrDefault(c => c.PersonId == pers.PersonId);
pId = pers.pId;
}
else
pId = con.Users.NextId(c => c.PersonId) + 1;
if (pers.UserId == 0)
con.Persons.AddObject(pers);
con.SaveChanges();
pId = Persons.PersonId;
var prof = new Profession() { Id = ProfessionId, PersonId = pId };
int profId = 0;
if (prof.PersonId > 0)
{
prof = con.Professions.FirstOrDefault(c => c.ProfessionId == prof.ProfessionId);
profId = prof.PersonId;
}
else
profId = con.Professions.NextId(c => c.ProfessionId) + 1;
if (prof.ProfessionId == 0)
con.Professions.AddObject(prof);
con.SaveChanges();
prof.ProfessionId = profId;
}
This should work:
using (PersonDataModelContainer dmc = new PersonDataModelContainer())
{
var pers = new Person() { Id = PersonId };
var prof = new Profession() { Id = ProfessionId };
pers.Professions.Add(prof);
dmc.Persons.Add(pers);
var result = dmc.SaveChanges();
}
Seem to have found the problem:
In the connection string I have |DataPath| which is set to the copy
at runtime.
Setting the DataPath to the actual path at the beginning of the Main function,
everything seems to be fine
This can be achieved with
AppDomain.CurrentDomain.SetData("DataDirectory", #"C:\myDB");
where C:\myDB is the path where the sdl file lives.
At the moment I have no idea, what to do about that on deployment, perhaps
it is enough to just comment out that line then, having the deploy path
as database path.