Navigate properties when using Dapper Extensions - c#

Im using DapperExtensions library for simple CRUD operations.
When I add a navigate property to my model, I get an error message that this column is not in the database. Can you in any way change this so that Dapper Extensions ignores this property?
Example of my model
public class Order : EntityBase
{
public int OrderId { get; set; }
public int MarketId { get; set; }
public int ModelId { get; set; }
public int ContactId { get; set; }
public string Project { get; set; }
public decimal Undertaking { get; set; }
public virtual Model Model { get; set; }
public virtual Contact Contact { get; set; }
}

Use the Write attribute above the property
[Write(false)]

add the package for dapperextentions
AutoMap(); will map all other properties as long as you have the same name for the field.
public class CustomMapper : DapperExtensions.Mapper.ClassMapper<Photo>
{
public CustomMapper()
{
Table("TableName if diffrent than the Model calss name");
Map(f => f.SomePropertyIDontCareAbout).Ignore();
AutoMap();
}
}

Related

CodeFirst EF Core - Implementing interfaces possible?

I'm a little new to code-first in EF Core and I'm trying a few things out and I'm a little confused how to implement the below (or indeed whether it can be implemented or not).
In my model I have a class that maps entities to cases, with the following mapping class
public class CaseEntity
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CaseEntityId { get; set; }
public int CaseId { get; set; }
public CaseModel Case { get; set; }
public Guid EntityId { get; set; }
public EntityModel Entity { get; set; }
}
I am now implementing the EntityModel object. However an entity can be either a Person or a Company. Both these have common properties, but there are some natural differences. What I wanted to do is create an IEntityModel interface and two classes as below
public class CaseEntity
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CaseEntityId { get; set; }
public int CaseId { get; set; }
public CaseModel Case { get; set; }
public Guid EntityId { get; set; }
public IEntityModel Entity { get; set; }
}
public interface IEntityModel
{
Guid EntityId { get; set; }
PostalAddress PrincipalAddress { get; set; }
}
public class CompanyEntity : IEntityModel
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid EntityId { get; set; }
public string CompanyName { get; set; }
public PostalAddress PrincipalAddress { get; set; }
}
public class PersonEntity : IEntityModel
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid EntityId { get; set; }
public PostalAddress PrincipalAddress { get; set; }
public string FirstNames { get; set; }
public string Surname { get; set; }
}
When I try to build this I get the error
The property 'CaseEntity.Entity' is of an interface type ('IEntityModel'). If it is a navigation, manually configure the relationship for this property by casting it to a mapped entity type.
Otherwise, ignore the property using the [NotMapped] attribute or 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
I'm not 100% certain I can do what I'm trying to do. Searching around has left me a little confused (is that a solution to implement kind of functionality like, or should I use implement an entity class that has all the properties need to support a Company or a Person?)
I think it would be better if you create a base class
public class EntityModel:IEntityModel
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int EntityId { get; set; }
publlic PostalAddress PrincipalAddress { get; set; }
}
CompanyEntity
public class CompanyEntity : EntityModel
{
public string CompanyName { get; set; }
}
CaseEntity
public class CaseEntity
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CaseEntityId { get; set; }
public int CaseId { get; set; }
public CaseModel Case { get; set; }
public int EntityId { get; set; }
public virtual EntityModel EntityModel { get; set; }
}

The Include method is missing on an EntityFramework Linq Query

Models
public class CreamModel
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public int? Type_Id { get; set; }
public CreamTypeModel CreamType { get; set; }
}
public class CreamTypeModel
{
[Key]
public int Id { get; set; }
public string Type { get; set; }
}
DbContext
internal class CreamEFDbContext : DbContext
{
public DbSet<CreamTypeModel> CreamTypeModels { get; set; }
public DbSet<CreamModel> CreamModels { get; set; }
}
SQL query
Second table
In my repository I want to take the list of creams and their type using the Include method but it's missing.
In my last project, the same method was available and working but now it isn't.
public class CreamRepository : ICreamRepository
{
private CreamEFDbContext context = new CreamEFDbContext();
public IEnumerable<CreamModel> CreamList
{
get { return context.CreamModels.Include(x => x.CreamType); }//have red line
}
}
The following images show what I have in my current project vs the old project where the Include method worked:
Current Project
Last Project
Include is an extension method from the QueryableExtensions class in the EntityFramework DLL. So you need to add a using statement to System.Data.Entity:
using System.Data.Entity;

EF Core - Single Selection of child collection stored at parent

Working with .NET Core 3.0 and EF Core if that impacts things.
I'm trying to define a model where:
A user owns a collection of toys.
A user can have a currently selected toy.
I'm trying to model this as such (BaseModel has common properties to all my entities), and AVUser is my ASP.NET Identity user class.
public abstract class BaseModel
{
public int Id { get; set; }
public DateTime LastModifiedDate { get; set; }
public DateTime CreatedDate { get; set; }
public AVUser CreatedUser { get; set; }
public AVUser ModifiedUser { get; set; }
}
public class Toy: BaseModel
{
[MaxLength(80)]
public string Name { get; set; }
}
public class AVUser : IdentityUser
{
public string FirstName { get; set; }
// The currently selected toy for the user.
public int SelectedToyId { get; set; }
public Toy SelectedToy { get; set; }
}
However, EF Core throws an error stating: Unable to determine the relationship represented by navigation property 'AVUser.Toy' of type 'Toy'.
I am having trouble how I annotate this so it knows that the user can have a collection of toys, and I want to store a single toy with the user as the currently selected one.
Write your model classes as follows:
public class Toy: BaseModel
{
[MaxLength(80)]
public string Name { get; set; }
[ForeignKey("AVUser")]
public string UserId { get; set; }
public AVUser AVUser { get; set; }
}
public class AVUser : IdentityUser
{
public string FirstName { get; set; }
// The currently selected toy for the user.
[ForeignKey("SelectedToy")]
public int SelectedToyId { get; set; }
public Toy SelectedToy { get; set; }
public ICollection<Toy> Toys {get; set;}
}
Then configure in the OnModelCreating in DbContext as follows:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<AVUser>().HasOne(a => a.SelectedToy).WithOne();
modelBuilder.Entity<AVUser>().HasMany(a => a.Toys).WithOne(t => t.AVUser).HasForeignKey(t => t.UserId);
}

Entity Framework MVC 4 Class Issue

I am trying to build a code first database with the Entity Framework with ASP.Net MVC 4.
I'm new to MVC & Entity Framework and I'm struggling with how to design my Class Objects.
I want a Members Class Like the one that follows, that has a data property of the AddressInformation Class :-
public class Member
{
public virtual int MemberID { get; set; }
public virtual string Forename { get; set; }
public virtual string Surname { get; set; }
public virtual int age { get; set; }
public virtual AddressInformation Address { get; set; }
public virtual string EmailAddress { get; set; }
public virtual string HomePhoneNumber { get; set; }
public virtual string MobileNumber { get; set; }
}
public class AddressInformation
{
public virtual int MemberID { get; set; }
public virtual string HouseNoName { get; set; }
public virtual string StreetName { get; set; }
public virtual string Town { get; set; }
public virtual string County { get; set; }
public virtual string PostCode { get; set; }
public virtual string Country { get; set; }
}
I also have another class that inherits from DbContext :-
public class CentralDataStore :DbContext
{
public DbSet<Member> Members { get; set; }
public DbSet<AddressInformation> AddressInfo { get; set; }
}
When I add the controller I am not getting the abilty to enter AddressInformation, only members info has populated through to my View's.
Anyone suggest the best method to attack this with? As I say, I'm new to MVC.
You do not need to make all of your properties virtual, only the ones used for navigation. And you need to setup up the relationship between Member and AddressInformation using the Fluency API. Also your primary key needs to be named Id or use an attribute or Fluency API to specify it is a primary key. You are also missing the id for mapping the Member to the AddressInformation. Here is what your class definition should look like.
public class Member
{
public int ID { get; set; }
public string Forename { get; set; }
public string Surname { get; set; }
public int age { get; set; }
public virtual int AddressId { get; set; }
public virtual AddressInformation Address { get; set; }
public string EmailAddress { get; set; }
public string HomePhoneNumber { get; set; }
public string MobileNumber { get; set; }
}
public class AddressInformation
{
public int ID { get; set; }
public string HouseNoName { get; set; }
public string StreetName { get; set; }
public string Town { get; set; }
public string County { get; set; }
public string PostCode { get; set; }
public string Country { get; set; }
}
Note I added the property AddressId to provide the mapping to the AddressInformation object/table. Configure the relationships in the Fluency API like this.
public class MemberConfig : EntityTypeConfiguration<Member>
{
internal MemberConfig()
{
this.HasKey(m => m.ID);
this.HasRequired(m => m.Address)
.WithRequiredDependent(a => a.ID)
.HasForeignKey(m => m.AddressId);
}
}
By setting up the foreign key relationship EF will automatically load the AddresssInformation into the Member object.
As far as I know the standard templates for generating the views does not implement the input fields for nested objects. But there is an option to expand the standard templates of MVC applications like in this link. There you can add the generation of input fields for nested classes if you are a fimilar to T4 templates.
You must be careful using this template, you can EASILY get a stackoverflow
Especially when using Entity Framework, when you have two entities with navigation properties that point to each other
The default Object template prevents recursion to a specific depth to prevent an infinite loop. I didn't like this so I wrote my own:
/Views/Shared/object.cshtml
#model object
#using System.Text;
#using System.Data;
#{
ViewDataDictionary viewData = Html.ViewContext.ViewData;
TemplateInfo templateInfo = viewData.TemplateInfo;
ModelMetadata modelMetadata = viewData.ModelMetadata;
System.Text.StringBuilder builder = new StringBuilder();
string result;
// DDB #224751
if (templateInfo.TemplateDepth > 2)
{
result = modelMetadata.Model == null ? modelMetadata.NullDisplayText
: modelMetadata.SimpleDisplayText;
}
foreach (ModelMetadata propertyMetadata in modelMetadata.Properties
.Where(pm => pm.ShowForEdit
&& pm.ModelType != typeof(System.Data.EntityState)
&& !templateInfo.Visited(pm)))
{
builder.Append(Html.Editor(propertyMetadata.PropertyName).ToHtmlString());
}
result = builder.ToString();
}
#Html.Raw(result)

asp.net c# and mongodb models

I wanna know if i can use mongodb like models (model classes) in my project (asp.net mvc 4 c#).
For example:
namespace Demo.Models
{
public class Model1
{
public int ID { get; set; }
public string Title { get; set; }
public DateTime ReleaseDate { get; set; }
public string Genre { get; set; }
public decimal Price { get; set; }
}
public class MovieDBContext : DbContext
{
public DbSet<Model1> models { get; set; }
}
}
Let's say this is standard model for mssql database. Can i create models like this to use MongoDB collections, documents?
If yes, how? (if you can provide me with link of some examples).
Thanks.
Yes you can don't forget to add BsonId attribute, because every object has to have his own unique id.
public class Model1
{
[BsonId]
public int ID { get; set; }
public string Title { get; set; }
public DateTime ReleaseDate { get; set; }
public string Genre { get; set; }
public decimal Price { get; set; }
}
And example you can find here:
http://www.joe-stevens.com/2011/10/02/a-mongodb-tutorial-using-c-and-asp-net-mvc/
Yes you can use mongodb as model in your project. you just have to define a model class and get the required enetities that you need.But in this you have provide an BsonId attribute for any object for generating a unique id.
here's is a example from my code just check it out.
public class QuestionAttempt
{
public ObjectId QId { get; set; }
public long UserId { get; set; }
[BsonElement("SN")]
public string SkillName { get; set; }
[BsonElement("IC")]
public bool IsCorrect { get; set; }
}
In my code i have given some objects a smaller name with the [BsonElement()] attribute for less memory usage.

Categories