Why isn't my Entity Framework Code First Pluralization working? - ef-code-first

I'm using Entity Framework Code First. Usually I have no problem, but for a database I'm working with I keep getting errors that it can't find the table in the SQL Server database. Here is what my class looks like:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public class CustomApp_User
{
[Key]
public int UserID { get; set; }
[MaxLength(50)]
public string Username { get; set; }
[MaxLength(250)]
public string Email { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateModified { get; set; }
}
In the database I have a table called "CustomApp_Users" to match the above. Note it has the "s" at the end.
And then I have:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
public class CustomAppDB : DbContext
{
public DbSet<CustomApp_User> CustomApp_Users { get; set; }
}
I expected EF codefirst to pluralize so that it would find "CustomApp_Users" in the database since this is how it usually works. But instead I get the error:
Invalid object name 'dbo.CustomApp_User'.
It appears it's not pluralizing the table name. I can't figure out why. One thing different with this database is that the Primary Keys do not follow the normal convention so I use the [Key] annotation.
I do know that if I use the [Table] annotation for my class it will work:
[Table("CustomApp_Users")]
But, I'd like to find out why the pluralization is not working the way I thought it would.

That is because the PluralizationService in EF can not pluralize it. It returns the same string if you pass it "CustomApp_User". Unfortunately you can not customize this service. So you need to configure the table name explicitly.

Related

Xamarin Forms Add List to SQL database

I have a problem. I created the following class:
public class KnownDevice
{
public int Id { get; set; }
public string Name { get; set; }
public string IP { get; set; }
public string MAC { get; set; }
public string Type { get; set; }
public List<TriangleRegistryObject> triangles { get; set; }
public List<HexagonRegistryObject> hexagons { get; set; }
}
Now, I want to create a Database on the mobile phone itself, so I use the following code to create the table:
database = DependencyService.Get<ISQLite>().GetConnection();
database.CreateTable<KnownDevice>();
But the code crashes on the second line with the error:
System.NotSupportedException: 'Don't know about
System.Collections.Generic.List`1
Now on the internet I found that it is not allowed to add a List to a database, but I need the data in that list, so I have no idea how I can fix this problem. The list can contain arround 25 rows!
Any idea how I can solve this problem?
List<TriangleRegistryObject> is not a valid type for a SQLite database value. Your type of List<TriangleRegistryObject> does not match any of the clrType == typeof(XXXX) statements, so you get that exception. You will need to rethink the class structure a little to be able to use SQLite-net like that.
For more details about the SQLite database, you could download the source file from the link for reference.
https://learn.microsoft.com/zh-cn/samples/xamarin/xamarin-forms-samples/todo/
If you want to use ou could use List, you could use SQLite-Net Extensions instead of SQLite.
You could refer to the link. The SQLite-Net Extensions library direct to specific relationships in database.
How can you store lists of objects in SQLite.net?

Serenity Framework date time display on column and Form

I'm working with Serenety Framework Core 2.0
The issue I have is that the date picker does not include the time.
So I create another field to add the time and included the only Display Format I have been able to make it work. An insert Form.cs looks like this
`using Serenity;
using Serenity.ComponentModel;
using Serenity.Data;
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.IO;
using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;
using System.ComponentModel.DataAnnotations;
[FormScript("Default.Events")]
[BasedOnRow(typeof(Entities.EventsRow), CheckNames = true)]
public class EventsForm
{
[TextAreaEditor(Rows = 3)]
public String Title { get; set; }
[TextAreaEditor(Rows = 8)]
public String Description { get; set; }
[Serenity.ComponentModel.DisplayFormat("dd/MM/yyyy HH:mm")]
public DateTime? EventDate { get; set; }
[Serenity.ComponentModel.DisplayFormat("HH:mm")]
public Time Time { get; set; }`
However nor the date picker or the time field show a time picker for lack of a better term.
I would like to have the time show either with the date picker or in its own filed.
Answer provide by Leo over Serenity Whatsup group. Simply to use DateTimeEditor
[DateTimeEditor(IntervalMinutes =1)]
public DateTime? EventDate { get; set; }

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?

VS Community 2015 MVC Template - Cannot access custom model

I'm currently learning Asp.NET MVC, I have started with the Ouf of the Box template from Vs2015 but I am having problems getting data from custom table
Goal: My Goal is to add a contact list for the standard ApplicationUser using the following class:
public class UserContact
{
[Key]
public virtual int Id { get; set; }
public virtual ApplicationUser User { get; set; }
public virtual ApplicationUser Contact { get; set; }
}
I have also added the following to my Application User:
public virtual ICollection<UserContact> ContactsList { get; set; }
And the following line to my ApplicationDbContext:
public DbSet<UserContact> UserContacts { get; set; }
The problem is that when I try to access the USerContacts table from my custome controller ContactController using
ApplicationDbContext db = new ApplicationDbContext();
var UserId = SomUserID
db.UserContacts.Where(x => x.User == UserId)
The where clause does not get recognised at all. I have useed the commands
enable-migration
add-migration ContactsList
update-database
Which ran with no errors and the table is now in the database. But I am unable to access the table. why? what am I doing wrong?
Please note that according to VS it is as if the .Where function is not available on the DbSet in my case
And linq is imported as this is the standard when adding a new empty controller with Vs2015.
The Database was created during the update-database
But ApplicationDbContext : IdentiyDbContext class does not let me access any other tables including Contact class, so,
when I used in my controller
"db.UserContacts.Where < x => x.User == someID >();"
it doesn recognise what x.User is from the UserContact class.
EDIT: I found a stack overflow post where the user was missing a using statement:
using System.Linq;
DbContext -> DbSet -> Where clause is missing (Entity Framework 6)

How can I name my Database using EF Code First?

I've got my EF Code First working exactly as expected aside from one small bit. I'm not sure how to name my Database File.
I'm using SQL CE, but I'm sure this applies to all forms of EF Code First.
Here's my DbContext
namespace MyApp.Domain.EntityFramework
{
public class DataContext : DbContext
{
//...
}
}
And when the database is created it's created as
MyApp.Domain.EntityFramework.DataContext.sdf
I'd prefer to just have it named
MyApp.sdf
Now I'm sure this is simple, but my Googling skills keep turning up examples where the database name is auto generated like mine.
http://www.hanselman.com/blog/SimpleCodeFirstWithEntityFramework4MagicUnicornFeatureCTP4.aspx
You need to specify a connection string (for example by creating a connection string named DataContext (your class name) in your config file, and set the desired name there.
I was looking to do the same. Managed to end up with this:
public class ShopDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<Feature> Features { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<Subcategory> Subcategories { get; set; }
public DbSet<Information> OrderInformation { get; set; }
public ShopDbContext() : base("Shop")
{
}
}
It will name your database "Shop" so just replace what is in the base("Shop") with whatever you want to call your database. Hope this helps.

Resources