Entity Framework 6 Code First duplicates - ef-code-first

I'm trying to learn EFCF but I stumbled upon a records duplication problem and I can't find solution anywhere on the internet (or I just don't know what to search). The DbContext class is as follows:
public class Database : DbContext
{
public Database() : base("name=DBconnString")
{
}
public DbSet<Human> People { get; set; }
public void human_add_new(int _rank, String _name, String _surname)
{
Human dummy = new Human(_rank, String _name, String _surname);
People.Add(dummy);
SaveChanges();
}
}
And the human class is as follows:
public class Human
{
[Index(IsUnique = true)]
public Int16 ID { get; set; }
public int rank { get; set; }
public String name { get; set; }
public String surname { get; set; }
}
Now, the problem is whenever I run my code and it executes this:
human_add_new(3, "Noname", "Noname");
a new record is created, thus creating duplicates in my database (so if I run the code 5 times, 5 identical records will be created). How do I prevent that? [Index(IsUnique = true)] doesn't seem to help here, cause in a larger database it may happen that 2 people have the same name or the same surname.
Here's how it looks like in MS SQL Studio: imgur

You applied a Unique Index to the ID property - if you want unique names/surnames, you'll have to apply a Unique constraint to them as well.
(According to your imgur picture, IDs are distinct, other fields are the same)

Related

Get the names of multiple columns for sorting in Datatables in Asp.Net MVC

I need to implement a way to get the list with the names of all the columns for sorting in the jquery datatables plugin. Currently, this only captures the name of the first column that should be sorted.
var sortingColumnName = Request.Form.GetValues("columns[" + Request.Form.GetValues("order[0][column]")?[0] + "][name]")?[0];
I can not set the string to Request.Form.GetValues.
I need this case, for example.:
"order": [[2, "asc"], [4, "desc"], [3, "desc"]]
When you inspect the elements you can verify that in this example there are three keys to order, but there may be other cases where you have more or fewer keys.
Don't use Request.Form. The issue you're currently having is that you're trying to manually deserialize posted data into some kind of usable data structure. The model binding in ASP.NET MVC already does exactly that.
A model structure that works for DataTables would look something like this:
public class DataTablesRequestViewModel
{
public int draw { get; set; }
public int start { get; set; }
public int length { get; set; }
public IList<DataTablesOrder> order { get; set; } = new List<DataTablesOrder>();
public class DataTablesOrder
{
public int column { get; set; }
public string dir { get; set; }
}
}
You can modify/extend/etc. as you need, but the default posted structure for DataTables should match this. Simply accept this model on your controller action:
public ActionResult YourActionMethod(DataTablesRequestViewModel request)
{
// in here you can get the list of sorted columns from: request.order
}

SQLite.net database with Xamarin.Forms App

I have a problem with an SQLite database in my Xamarin.Forms PCL project.
I have followed this example from Microsoft Docs:
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/databases
I've been using my own types to store data and it's worked Ok for simple custom types, but I've recently added List<int> and Attendance type to the custom object (Info).
Now when I try and create the object, i get the following errors:
Don't know about System.Collections.Generic.List`1[System.Int32]
Don't know about MyApp.Attendance
Here is the init code:
readonly SQLiteAsyncConnection database;
database = new SQLiteAsyncConnection(dbPath);
database.CreateTableAsync<UserPrefrences>().Wait();
database.CreateTableAsync<Attendance>().Wait();
database.CreateTableAsync<Info>().Wait();
I'm using Xamarin.Forms with Xamarin.iOS.
You can not store them by default like that. However there is sqlite-net-extensions which you can use to accomplish that. You can take a look about sqlite-net-extensions here.
Using this extension you will be able to do that with TextBlob property, something like this:
public class Address
{
public string StreetName { get; set; }
public string Number { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }
}
public class Person
{
public string Name { get; set; }
[TextBlob("PhonesBlobbed")]
public List<string> PhoneNumbers { get; set; }
[TextBlob("AddressesBlobbed")]
public List<Address> Addresses { get; set; }
public string PhonesBlobbed { get; set; } // serialized phone numbers
public string AddressesBlobbed { get; set; } // serialized addresses
}
More explanation about TextBlob from url.
Text blobbed properties Text-blobbed properties are serialized into a text property when saved and deserialized when loaded. This allows
storing simple objects in the same table in a single column.
Text-blobbed properties have a small overhead of serializing and
deserializing the objects and some limitations, but are the best way
to store simple objects like List or Dictionary of basic types or
simple relationships.
Text-blobbed properties require a declared string property where the
serialized object is stored.
I just saw that there is also similar/same questions about this topic on StackOverflow already, so you can take a look at them also.
How can you store lists of objects in SQLite.net?
Can I use a List of String in a class intended for SQLite?

Using OData how can I sort a property that holds a list?

Here is the problem I need to solve:
I need to display a grid that contains a group of columns that are dynamic, meaning that the number can change depending on the user parameters.
I have attached a sample below as an image to illustrate:
GRID SAME IMAGE
I have these c# POCOs to keep my question simple
public class OrderItem
{
public string ProductName { get; set; }
public string Status { get; set; }
public List<CityOrderInfo> CityOrders { get; set; }
}
public class CityOrderInfo
{
public int OrderCount { get; set; }
}
I have a web api controller that is able to accept the OData request, plus other arguments that the repository accepts. However the problem is that while the parameter $orderby for ProductName and Status works, when I do "$orderby='CityOrders[1]\OrderCount asc' it fails.
public class OrdersControllers : ApiController
{
private readonly IOrdersRepository _repository;
public OrdersControllers(IOrdersRepository repository)
{
this._repository = repository;
}
public IEnumerable<OrderItem> GetOrderItems([FromUri] ODataQueryOptions<OrderItem> oDataQuery)
{
var result = this._repository.GetOrders().ToList();
var queryableData = oDataQuery.ApplyTo(result.AsQueryable());
var transformedData = queryableData as IEnumerable<OrderItem>;
return transformedData;
}
}
The reason I opted to hold the city orders in list is because I thought it would too painful to make a POCO with every city in the USA as a property so instead made it more generic.
The question is how can a sort on a property that holds a list using OData? Is this possible? I keep getting syntax error at position n. As of now I have not found an answer.

The member with identity does not exist in the metadata collection. Parameter name: identity

We are using EF Code First 4.3.1.
We are developing an ASP.NET Web Role referring to multiple class libraries.
There are two class libraries each containing classes and an individual DBcontext.
Lets say the Library1 has classes A and B.
DBcon1: DbSet and DbSet
Lets say the Library2 has classes C and D.
Class C{
[Key]
public int CId{ get; set;}
[Required]
public virtual A referencedA {get; set;}
}
DBcon2: DbSet<C> and DbSet<D>
When I try to use the DBcon2 as such:
using (var con = new DBcon2())
{
C vr = new C();
vr.CId= 1;
vr.referencedA = DBCon1.As.First();
con.Cs.Add(vr);
con.SaveChanges();
}
I get an exception as:
"The member with identity does not exist in the metadata collection.
Parameter name: identity"
Both DBCon1 and DBcon2 are using the sane SQL Server Database "SampleDB".
Please point me in the right direction.
I got this error and fixed it by not trying to set the navigation property in the related table, just set the foreign key id instead
eg
public class Student()
{
public int StudentId { get; set; }
public string StudentName { get; set; }
public int CourseId { get; set; }
public virtual Course Course { get; set; }
}
public class Course()
{
public int CourseId { get; set; }
public string CourseName { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
Main code:
var myCourse = new Course();
var myCourseId = 1;
var student = new Student() {
CourseId = myCourseId
// Course = myCourse <-- this would cause the error
}
Might not be your issue but maybe it will point you in the right direction and hopefully will help someone else.
The exception is a bit cryptic, but pretty clear if you realise that a context needs information about entities (metadata) to be able to write sql statements. Thus, your DBcon2 context has no clue where to find the primary key of an A, because it has no metadata about A.
You could however set an integer property A_Id (or the like), but then you'll have to write custom code to resolve it to an A.
Another option is to merge (parts of) the contexts, if possible.

Populate dropdownlist from another dropdownlist with objects in MVC 2

I am trying to develop a simple MVC 2 timesheet application for my small business.
I have a sort of mock model for now until I have a database in place, just to make things simpler while I develop the functionality. It consists of the following:
public class CustomersRepository
{
public CustomersRepository()
{
Customers = new List<Customer>();
}
public List<Customer> Customers { get; set; }
}
public class Task
{
public Task()
{
Customer = new Customer();
TimeSegments = new List<TimeSegment>();
}
public override string ToString()
{
return Name;
}
public string Name { get; set; }
public Customer Customer { get; set; }
public List<TimeSegment> TimeSegments { get; set; }
}
public class TimeSegment
{
public string Id { get; set; }
public string Date { get; set; }
public int Hours { get; set; }
}
public class Customer
{
//To show the name in the combobox instead of the object name.
public override string ToString()
{
return Name;
}
public Customer()
{
Tasks = new List<Task>();
}
public List<Task> Tasks { get; set; }
public string Name { get; set; }
}
I initialize the repository in the controller, and pass the "model" to the view:
CustomersRepository model = new CustomersRepository();
public ActionResult Index()
{
InitializeRepository();
return View(model);
}
Now, in the view I populate a dropdownlist with the customers:
<div>
<%:Html.DropDownListFor(m => m.Customers, new SelectList(Model.Customers), new {#id="customerDropDownList"}) %>
</div>
But then I need to populate a second dropdownlist (taskDropDownList for the tasks associated with a particular customer) based on the selection the user chooses in the customer dropdownlist.
But how do I do this exactly? I have seen examples with jQuery, but I'm not sure how to apply them to this situation. Also, the examples seem to just populate the lists with string values. I need to be able to access the objects with all their properties. Because the next thing I need to do is to be able to populate the TimeSegments list of the selected task with values from input fields (i.e. the hours worked for particular dates). And for that to be saved to the "model" (eventually to the database) in the controller, how do I get it there, unless the objects are all part of the same model bound to the View?
I'm on rather thin ice with this since I still find the connection between the View and the Controller hard to handle, compared with e.g. Windows development, where these things are rather easy to do. So I would really appreciate a good step by step example if anyone would be so kind as to provide that!
I found the answer here:
http://www.pieterg.com/post/2010/04/12/Cascading-DropDownList-with-ASPNET-MVC-and-JQuery.aspx
It needed some tweaks, and I got help here from CGK. See this post:
Cascading dropdownlist with mvc and jQuery not working

Resources