How to setup my code as DB First in an ORM - entity-framework

I have looked at using EF, nHibernate and Dapper/Dapper.SimpleCRUD. In none of them can I figure out how to represent my use case in regards to my database (SQL Server 2012) model. I am building an ASP.NET website with a grid in C# 4.0/.NET 4.0 (due to technical limitations) that will have CRUD capabilities, with the initial state of the grid being set by dropdowns.
My two tables are set up as such:
Address_Book
|_[EntryID]
|_[Last_Name]
|_[First_Name]
|_[Title]
|_[Office_Num]
|_[Cell_Num]
|_[Home_Num]
|_[Email_Address]
|_[Special_Info]
|_[hr24_Emails]
|_[hr48_Emails]
|_[RM_Emails]
|_[Prestige_Emails]
|_[GEB_Emails]
|_[LAW_Emails]
Distribution
|_[Brand]
|_[Location_Mnemonic]
|_[Location_Code_Numeric]
|_[EntryID]
|_[Division_Mnemonic]
|_[Region_Mnemonic]
|_[Zone_Mnemonic]
|_[District_Mnemonic]
|_[Key]
With a many-to-one relationship between Distribution and Address_Book where Address_book.EntryID = Distribution.EntryID.
Any help with how to set this up would be appreciated. I am having issues managing the CRUD operations manually, so I thought an ORM would help, but I cannot figure it out. Any help is appreciated.
Thanks in advance!

The whole .net CRUD thing is a big realm with a lot of flavors and ways of doing the work. And while I don't know exactly where you are at with this, the following my help out. In my experience EF can handle relationships quite well, though the whole EF learning process is a bit steep and I've shied away from it. I typically use Dapper with extensions and do stuff pseudo-manually. I haven't used the SimpleCrud extension. Since you inherited the DB, hopefully it's set up well and there's a FK constraint on Distribution, Column EntryID.
In Dapper, you could set up your classes like:
using Dapper.Contrib.Extensions;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
namespace Jacrys
{
[Table("dbo.address_book")]
public partial class AddressBook
{
[Dapper.Contrib.Extensions.Key]
public int EntryID { get; set; }
public string Last_Name { get; set; }
public string First_Name { get; set; }
public string Title { get; set; }
public string Office_Num { get; set; }
public string Cell_Num { get; set; }
public string Home_Num { get; set; }
public string Email_Address { get; set; }
public bool Special_Info { get; set; }
public bool hr24_Emails { get; set; }
public bool hr48_Emails { get; set; }
public bool RM_Emails { get; set; }
public bool Prestige_Emails { get; set; }
public bool GEB_Emails { get; set; }
public bool LAW_Emails { get; set; }
//use this only if you need all of the distributions to be
//part of your main AddressBook class
public IEnumerable<Distribution> Distributions { get; set; }
public static AddressBook GetById(short id)
{
using (IDbConnection cn = new SqlConnection("getConnString"))
{
cn.Open();
return cn.Get<AddressBook>(id);
}
}
public static IEnumerable<AddressBook> GetAll()
{
using (IDbConnection cn = new SqlConnection("getConnString"))
{
cn.Open();
return cn.GetAll<AddressBook>();
}
}
public int Insert()
{
using (IDbConnection cn = new SqlConnection("getConnString"))
{
cn.Open();
return (int)cn.Insert(this);
}
}
public bool Update()
{
using (IDbConnection cn = new SqlConnection("getConnString"))
{
cn.Open();
return cn.Update(this);
}
}
public bool Delete()
{
using (IDbConnection cn = new SqlConnection("getConnString"))
{
cn.Open();
return cn.Delete(this);
}
}
}
[Table("dbo.distribution")]
public partial class Distribution
{
[Dapper.Contrib.Extensions.Key]
public int Key { get; set; }
public int EntryID { get; set; }
public string Brand { get; set; }
public string Location_Mnemonic { get; set; }
public int Location_Code_Numeric { get; set; }
public string Division_Mnemonic { get; set; }
public string Region_Mnemonic { get; set; }
public string Zone_Mnemonic { get; set; }
public string District_Mnemonic { get; set; }
//similar CRUD methods to AddressBook follow here
}
}
Then with a GridView like:
<asp:GridView ID="gvAddresses" runat="server" AutoGenerateColumns="true" DataKeyNames="EntryID">
</asp:GridView>
You can load it up in the code behind with (and adding lambda expression for pre-sorting):
gvAddresses.DataSource = Jacrys.AddressBook.GetAll().OrderBy(c=>c.Last_Name);
Any dropdowns you need can be loaded in similar ways.
Everything depends on your needs. If you have a gridview of Distribution, then you can add in a dropdown for Address when in edit mode (in the row data bound event). When you go to update and save, you'll have to find the control in the row and parse it's selected value before saving the record. There really isn't a nifty one single way to get this done. Though, if you have all of your business classes set up with CRUD methods you can wire it all together more simply.

Related

Entity Framework fails to get child elements

I have SQLite db and these EF models and context.
Models and Context
public class CardHolder
{
public int CardHolderId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string PhoneNumber { get; set; }
public string EmailAddress { get; set; }
public string TenantName { get; set; }
public ICollection<AccessCard> AccessCards { get; set; }
}
public class AccessCard
{
public int AccessCardId { get; protected set; }
public CardHolder CardHolder { get; set; }
public DateTime ActivationDate { get; protected set; }
public bool ActivationProcessed { get; set; }
public DateTime? DeactivationDate { get; protected set; }
public string DeactivationReason { get; set; }
public bool DeactivationProcessed { get; set; }
}
public class MyContext : DbContext
{
public DbSet<CardHolder> CardHolders { get; set; }
public DbSet<AccessCard> AccessCards { get; set; }
}
And the Main program
class Program
{
static void Main(string[] args)
{
using (var db = new MyContext())
{
var cardHolders = db.CardHolders.Include("AccessCard").ToList();
}
}
}
Question1: Why do I get this exception
System.InvalidOperationException: 'A specified Include path is not
valid. The EntityType 'SQLiteDemo.Models.CardHolder' does not declare
a navigation property with the name 'AccessCard'.'
If I replace it with
var cardHolders = db.CardHolders.Include("AccessCards").ToList();
I get another error:
SQL logic error no such column: Extent2.CardHolder_CardHolderId
What is wrong with Entity Framework?
Question2: Why cant I use arrow function in Include statement, it doesnt compile at all?
var cardHolders = db.CardHolders.Include(x => x.AccessCards).ToList();
Question3: Why do I need to use Include at all if my ICollection association property AccessCards is NOT virtual - that means eager loading must work by itself!
Why the hell it is so problematic and buggy? Nothing works as it should :(
1 - You have a typo as you have already determined :)
1B - "SQL logic error no such column: Extent2.CardHolder_CardHolderId"
EF isn't finding your FK. You could add it to your AccessCard model:
public int CardHolderId { get; set; }
2 - You need to pull in the LINQ extensions. Make sure you have both of these using statements at the top:
using System.Data.Entity;
using System.Linq;
3 - You, like many others, are misunderstanding lazy loading. Eager loading still requires an Include() to fetch related data. Lazy loading only fetches the relations when you access them.

Entity Framework Navigation Property Error

I am getting this error in my .Net MVC 4 web application:
The property 'Username' cannot be configured as a navigation property. The
property must be a valid entity type and the property should have a non-abstract
getter and setter. For collection properties the type must implement
ICollection<T> where T is a valid entity type.
I am very new to Entity Framework and I can't seem to get around this issue. Here is some code:
//DB Context
public class EFDbContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().HasMany(u => u.Roles).WithMany(r => r.Users).Map(x => x.MapLeftKey("Username").MapRightKey("RoleName").ToTable("Users_Roles"));
}
}
//Entity Classes
public class User
{
[Key]
public string Username { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public string Comment { get; set; }
public int Level { get; set; }
public string PasswordQuestion { get; set; }
public string PasswordAnswer { get; set; }
public bool IsApproved { get; set; }
public DateTime LastActivityDate { get; set; }
public DateTime LastLoginDate { get; set; }
public DateTime LastPasswordChangedDate { get; set; }
public DateTime CreationDate { get; set; }
public bool IsOnLine { get; set; }
public bool IsLockedOut { get; set; }
public DateTime LastLockedOutDate { get; set; }
public int FailedPasswordAttemptCount { get; set; }
public DateTime FailedPasswordAttemptWindowStart { get; set; }
public int FailedPasswordAnswerAttemptCount { get; set; }
public DateTime FailedPasswordAnswerAttemptWindowStart { get; set; }
[InverseProperty("RoleName")]
public virtual ICollection<Role> Roles { get; set; }
public override string ToString()
{
return this.Username;
}
}
public class Role
{
[Key]
public string RoleName { get; set; }
public int Level { get; set; }
[InverseProperty("Username")]
public virtual ICollection<User> Users { get; set; }
public override string ToString()
{
return this.RoleName;
}
}
//Repository
public class EFUsersRepository : IUsersRepository
{
private EFDbContext context = new EFDbContext();
public IQueryable<User> Users
{
get { return context.Users; }
}
public User GetUser(string username)
{
return context.Users.Find(username); //THIS IS WHERE THE CRASH OCCURS
}
}
//DB Setup
Table Users, Role and Users_Role. Users_Role is a simple linking table with [username, role] columns both of type varchar.
The database tables columns & types match the two classes above (User,Role).
I inherited this project which was unfinished but I can't get it to run successfully. Any help understanding what the issue is would be helpful. Thanks!
It might be that Entity Framework is updated. Easiest way will be to recreate the DataModel.
Even if the previous programmer did not use Entity Data Mode, you can at least copy the auto generated code such as EFDbContext, Users and Roles classes.
It turns out, after commenting out enough items all day long, the the following lines are what caused this error for me:
[InverseProperty("RoleName")] //In file User.cs (as shown above)
[InverseProperty("UserName")] //in file Role.cs (as shown above)
I am still learning Entity Framework and I don't know why this was the solution, but it stopped the error which I reported above.
I hope that this helps someone else and if anyone wants to help me understand what the issue was in detail, please feel free. I am eager to learn.

Asp.net MVC 4 Code First Return Specific Fields from Navigation Property

Been stuck on this for a while so i thought i would ask. I am sure there is something simple i am missing here. Trying to learn Asp.net mvc 4 on my own by building a simple app.
Here is the model:
public class Category
{
public int Id { get; set; }
[Required]
[StringLength(32)]
public string Name { get; set; }
//public virtual ICollection<Note> Notes { get; set; }
private ICollection<Note> notes;
public ICollection<Note> Notes
{
get
{
return this.notes ?? (this.notes = new List<Note>());
}
}
}
public class Note
{
public int Id { get; set; }
[Required]
public string Content { get; set; }
[Required]
[StringLength(128)]
public string Topic { get; set; }
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
public virtual IEnumerable<Comment> Comments { get; set; }
public virtual ICollection<Tag> Tags {get; set;}
public Note()
{
Tags = new HashSet<Tag>();
}
}
public class Tag
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Note> Notes { get; set; }
public Tag()
{
Notes = new HashSet<Note>();
}
}
I call this method in a repository from the controller:
public IQueryable<Note> GetAll()
{
var query = _db.Notes.Include(x => x.Category).Include(y => y.Tags);
return query;
}
On the home controller i am trying to return a list of all the notes and wanted to include the category name that it belongs to as well as the tags that go with the note. At first the did not show up so i read some tutorials about eager loading and figured out how to get them to show.
However, my method is not that efficient. The mini-profiler is barking at me for duplicate queries because the navigation properties for category and tags are sending queries for the notes again. IS there any way to just return the properties i need for the category and tag objects?
I have tried several methods with no luck. I was hoping i could do something like this:
var query = _db.Notes.Include(x => x.Category.Name).Include(y => y.Tags.Name);
But i get an error: Cannot convert lambda expression to type 'string' because it is not a delegate type
I have seen that error before that was caused by some missing using statements so i already double checked that.
Any suggestions? Thanks for the help

Entity framework Database First & EF Code First get Relation Object By ID

in EF Database First when change ForeignKey(CommodityGroupID) automatic Get CommodityGroup for Commodity object, But in EF Code First(4.3.1) not doing.
public class Commodity
{
public int CommodityID { get; set; }
public string MadeBy { get; set; }
public decimal ServiceTimePrice { get; set; }
public decimal QCPrice { get; set; }
public int ServicePoint { get; set; }
public string Note { get; set; }
public int CommodityGroupID { get; set; }
[ForeignKey("CommodityGroupID")]
public virtual CommodityGroup CommodityGroup { get; set; }
}
public class CommodityGroup
{
public int CommodityGroupID { get; set; }
public string CommodityGroupName { get; set; }
public virtual ICollection<Commodity> Commodities { get; set; }
}
this Property defined in Edmx file (database first), i Should define this code in ef code first?
[BrowsableAttribute(false)]
[DataMemberAttribute()]
public EntityReference<CommodityGroup> CommodityGroupReference
{
get
{
return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<CommodityGroup>("GaamRepairModel.FK_Commodity_CommodityGroup", "CommodityGroup");
}
set
{
if ((value != null))
{
((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedReference<CommodityGroup>("GaamRepairModel.FK_Commodity_CommodityGroup", "CommodityGroup", value);
}
}
}
It sounds like you're wanting a change tracking proxy. You want the CommodityGroup navigation property to update automatically when the FK is changed correct?
See this post on MSDN for details about the change tracking proxy.
This post on MSDN shows some code on how to test of your proxy object is being created properly.
Is this a new object? If so, you'll need to call the CreateObject function on your DbSet, not use the New Commodity().

EF Code First: Treating entity like a complex type (denormalization)

I'm using EF 4.1 Code First, and I'm making a configurable utility for parsing/importing large delimited files. Each row in the file may contain data for several entities.
The exact data and layout for the file will be unknown at build time (it's configured differently for each client), so I'm making it configurable.
Example model (simplified)
public class Contact {
public int Id { get; set;}
public string Name { get; set; }
}
public class Account {
public int Id { get; set; }
public decimal Balance { get; set; }
public bool IsOpen { get; set; }
}
Depending on the client, a file may contain contact info, account info, or both. Because of the size of these files (tons of records), we have to use SqlBulkCopy to do the data loading. It's also unknown at compile time exactly what rules will be run against the data (validation changes by client, etc.)
I want to have a table and class, like ImportRecord, to hold the imported data. My current working class is like:
public class ImportRecord {
public string Contact_Name { get; set; }
public decimal Account_Balance { get; set; }
public bool Account_IsOpen { get; set; }
}
The issue here is that as we add/change fields in the model classes, the ImportRecord has to get changed also -- it's duplicative/less than ideal. It's somewhat important to me that the import data resides in a single table to simplify the SqlBulkCopy import.
My ideal ImportRecord class would look like this:
public class ImportRecord {
public Contact Contact { get; set; }
public Account Account { get; set; }
}
But that would just create a table with two foreign keys (aside from complaining about no FK properties). Is there a way to have the entity classes behave more like a denormalized, keyless, complex type for the ImportRecord? Am I going about this entirely wrong?
Thanks!
Entity cannot be nested and in the same time complex type cannot have entity key so you cannot use one instead of other but you can try this little cheat. I just tested that it at least creates correct database structure:
public class Context : DbContext
{
public DbSet<Account> Accounts { get; set; }
public DbSet<Contact> Contacts { get; set; }
public DbSet<ImportRecord> ImportRecords { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ComplexType<ContactBase>();
modelBuilder.ComplexType<AccountBase>();
}
}
public class ContactBase
{
public string Name { get; set; }
}
public class AccountBase
{
public decimal Balance { get; set; }
public bool IsOpen { get; set; }
}
public class Contact : ContactBase
{
public int Id { get; set; }
}
public class Account : AccountBase
{
public int Id { get; set; }
}
public class ImportRecord
{
public int Id { get; set; }
public ContactBase Contact { get; set; }
public AccountBase Account { get; set; }
}