MVC Validation on Model in Portable Class Library - asp.net-mvc-4

I am new to MVC but have worked my way through the validation tutorials and they do exactly what I want to do... but.... my model is in a separate portable class library.
How would I add the validation rules to this non-MVC solution so that my MVC website?
Is it possible please?
Thanks

You can create an interface to that class and use impromptu interface to have your class act as that interface...
Lets say this is the class from the portable library:
public class SomeClass
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Create a cloned interface and specify validation attributes in it:
public interface ISomeClass
{
[Required]
string FirstName { get; set; }
string LastName { get; set; }
}
At the top of your view, pass the interface instead of the class:
#model YourNamespace.Models.ISomeClass
In your controller, do:
return View(instanceOfSomeClass.ActLike<ISomeClass>();
You can find impromptu interface here:
http://code.google.com/p/impromptu-interface/
Since the class and the interface look exactly the same, model binding works as well.
Hope this helps.

Related

Automapper not mapping between two objects (which are virtually the same for all intents and purposes)

Yes, this is ANOTHER "Automapper not mapping" question. Either something broke or I'm going the stupid way about it. I'm building a webapp with ASP.NET Core 2.1 using AutoMapper 3.2.0 (latest stable release at the time) though I have tested with 3.1.0 with no luck either.
Question
Simple object to be mapped to another. For the sake of testing and trials, these are now EXACTLY the same, yet still automapper gives:
AutoMapperMappingException: Missing type map configuration or unsupported mapping.
Mapping types:
NotificationModel -> NotificationViewModel
ProjectName.Models.Dashboard.NotificationModel -> ProjectName.Models.Dashboard.NotificationViewModel
The strange thing is, I have previously mapped this model set 7 ways to sunday in the Startup.cs file with the only thing changing is my facial expression. Other maps work as indicated using similar, if not the same code for them.
The Models
NotificationModel.cs
public class NotificationModel
{
public int Id { get; set; }
public string Content { get; set; }
public DateTime CreateTS { get; set; }
public bool FlagRead { get; set; }
public bool FlagSticky { get; set; }
public bool FlagReceipt { get; set; }
public string ReceiptContact { get; set; }
public string UserId { get; set; }
public bool CANCELLED { get; set; }
}
NotificationViewModel.cs
public class NotificationViewModel
{
public int Id { get; set; }
//Reminder, this model has been amended to exactly represent that of the original model for testing purposes.
public string Content { get; set; }
public DateTime CreateTS { get; set; }
public bool FlagRead { get; set; }
public bool FlagSticky { get; set; }
public bool FlagReceipt { get; set; }
public string ReceiptContact { get; set; }
public string UserId { get; set; }
public bool CANCELLED { get; set; }
}
Startup & Automapper Config
Mapper.Initialize(cfg =>
{
// Some other mappings removed for clarity.
cfg.CreateMap<GroupViewModel, GroupModel>().ReverseMap();
//cfg.CreateMap<EntityViewModel, EntityModel>().ReverseMap().ForAllOtherMembers(opt => opt.Ignore());
cfg.CreateMap<NotificationModel, NotificationViewModel>().ForAllMembers(opt => opt.Ignore());
cfg.CreateMap(typeof(NotificationViewModel), typeof(NotificationModel));
//I even left out the .ReverseMap, for testing purposes.
});
Mapper.AssertConfigurationIsValid();
Usage
NotificationViewModel test = _mapper.Map<NotificationViewModel>(item); << Which is where I receive the exception.
Other Attempts
Ok, so I've been through some more articles explaining different things and subsequently tried the following respectively:
cfg.CreateMap(typeof(NotificationModel), typeof(NotificationViewModel));
cfg.CreateMap<NotificationModel, NotificationViewModel>().ReverseMap().ForAllMembers(opt => opt.Ignore());
cfg.CreateMap<NotificationModel, NotificationViewModel>().ForAllOtherMembers(opt => opt.Ignore());
Along with:
NotificationViewModel test = _mapper.Map<NotificationViewModel>(item);
_mapper.Map(item, typeof(NotificationViewModel), typeof(NotificationModel));
NotificationViewModel existingDestinationObject = new NotificationViewModel();
_mapper.Map<NotificationModel, NotificationViewModel>(item, existingDestinationObject);
I've tried amending the .Map()/.Map<> usage several ways, none of which seemed to yield anything but an exception about not having been configured.
So short of manually writing a conversion for this object (which is simple enough for its purpose), I am in dire need of a solution here. If not to use, then atleast to learn from and help others facing the same.
UPDATE
IT WORKS!
Scanning through the project, I noticed that somewhere in previous documentation - I read about creating a type of "config" class that just inherits from an abstract class called Profile. In this class you will also be able to define your maps, yet what is strange is that I am not able to drop this class and simply use the config maps setup in my Startup.cs file. Automapper will refuse to hold any maps that are not defined in this separate class. The below seems to get me what I need, however I still need an explanation as to why Automapper doesn't function as desired without it:
public class AMConfig : Profile
{
public AMConfig()
{
CreateMap<ManageUserModel, IndexViewModel>();
CreateMap<IndexViewModel, ManageUserModel>();
CreateMap<NotificationViewModel, NotificationModel>().ReverseMap();
CreateMap<List<NotificationViewModel>, List<NotificationModel>>().ReverseMap();
CreateMap<TaskViewModel, TaskModel>().ReverseMap();
}
}
Thanks!
Scanning through the project, I noticed that somewhere in previous documentation - I read about creating a type of "config" class that just inherits from an abstract class called Profile. In this class you will also be able to define your maps, yet what is strange is that I am not able to drop this class and simply use the config maps setup in my Startup.cs file. Automapper will refuse to hold any maps that are not defined in this separate class. The below seems to get me what I need, however I still need an explanation as to why Automapper doesn't function as desired without it:
public class AMConfig : Profile
{
public AMConfig()
{
CreateMap<ManageUserModel, IndexViewModel>();
CreateMap<IndexViewModel, ManageUserModel>();
CreateMap<NotificationViewModel, NotificationModel>().ReverseMap();
CreateMap<List<NotificationViewModel>, List<NotificationModel>>().ReverseMap();
CreateMap<TaskViewModel, TaskModel>().ReverseMap();
}
}

EF Core no .Include() method on DBset

I'm currently completely unable to call .Include() and intellisense (in vscode) doesn't seem to think it exists.
Now after a long time searching the web I've found this:
Not finding .Include() method in my EF implementing Generic repository
which seems to suggest that .Include exists only in System.Data.Entities, which is only available for EF 5 and 6.
So how do i eager load my list property for an entity in EF core?
heres my context
public class Database : DbContext
{
//Set new datasources like this: public DbSet<class> name { get; set; }
public DbSet<Domain.Resource> Resources { get; set; }
public DbSet<Domain.ResourceType> ResourceTypes { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Filename=./something.db");
}
}
Heres the data classes:
public class Resource
{
public int ResourceId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int ResourceTypeId { get; set; }
public ResourceType ResourceType { get; set; }
}
public class ResourceType
{
public int ResourceTypeId { get; set; }
public string Name { get; set; }
public List<Resource> Resources { get; set; }
}
Then I do something like:
public List<ResourceType> GetAll()
{
var router = new Database();
var result = router.ResourceTypes.Include(rt => rt.Resources); //It's here there's absolutely no .Include method
return result.ToList();
}
Does .Include not exist in EF Core?
It's a direct consequence of a missing reference in the file where I'm making a call to the method (though i'm not quite sure i understand how...)
Anyways, adding:
using Microsoft.EntityFrameworkCore;
like Tseng and Smit suggested, did the trick. (in the file in which i define the function)
Though why that works i have no idea. I thought .include would automatically be available through the DbSet.
Thanks though! :)
Small, late EDIT: as Christian Johansen pointed out in his comment, the reason it needs the import to see the method signature, is that it is an extension method, which is a topic I strongly encourage any up-and-coming C# developer to learn about as it is immensely useful.
If you end up here, a user of EF 6 or below and happen to miss that OP actually mentioned this like I did, you want to add
using System.Data.Entity;
to your class.
Here is a previous answer that is tracking this issue in EF7. It appears it is now 'included'.

Silverlight WCF reused types no methods

I feel like this should be really simple but I am having an issue figuring out what is going on. I am working with a WCF service and have "Reuse types in all referenced assemblies" on. I have some simple classes to transfer some data. The classes show up fine and all the basic members show up, but no methods do. Are methods not included in this? Do I have to specify this is what I want somehow? Here is some example code. I just switched out my names to make it a little more generic.
public class Car
{
public string CarColor { get; set; }
public string Model { get; set; }
public int Year { get; set; }
public string GenerateId()
{
return CarColor + Model + Year;
}
}
In this example I get CarColor, Model, and Year on the client side but not GenerateId.
So I ended up doing this a little different. It totally makes sense that only the data comes over. The problem is that I didn't want to have to have a new project to hold the data types. Its just a pain to have a new repository and a completely separate project for a handful of classes. Since I really only need the methods on the client side, I am just creating partial classes with them in it on the client side. That way I can pull the data structure from the service but still extend it to have the methods I need.
Service definition
public class Car
{
public string CarColor { get; set; }
public string Model { get; set; }
public int Year { get; set; }
}
Client partial class
public partial class Car
{
public string GenerateId()
{
return CarColor + Model + Year;
}
}

I can't create controller in asp.net mvc 4

I want create controller in mvc 4 (vs 2012)
"MVC controller with read/write action and view using Entity Framwork"
But I can't choose my model class.
my model class
public class Authorss
{
public int id { get; set; }
public string name{get;set;}
}
public class ModelContext : DbContext
{
public DbSet Authors { get; set; }
}
I decided this problem. When I create model class, I don't rebuild my project and when I want to choose model class, it was don't visible.

Is the properties in Entity must be virtual when using FluentNhibernate?

Which entity FluentNHibernate uses as entity
I create some entity in Domain(or BLL), such as the following:
public class Role
{
public long ID { get; protected set; }
public string Name { get; set; }
public string Description { get; set; }
public List<User> Users { get; set; }
public Role()
{
Users = new List<User>();
}
}
And I want make use of FlunetNHibernate to map them, but get errors:
The following types may not be used as proxies:
Freeflying.Domain.Core.Profile: method get_ID should be 'public/protected virtual' or 'protected internal virtual'
Yes, I recall the programmer requirement when use FluentNHibernate, the entity should be like this:
public class Role
{
public virtual long ID { get; protected set; }
public virtual string Name { get; set; }
public virtual string Description { get; set; }
}
But It looks wired. Do you think so? How do you do when using FluentNHibernate? I don't want go back to Domain layer and add virtual for every property.
This is a basic requirement for using NHibernate; It allows NHibernate to generate a proxy class that descends from your class for lazy loading and such.
I have not seen a method of removing this requirement, though if such a thing is possible it would mean that you could not use lazy loading of objects and/or properties.
Here's a blog post that explains this a bit more; It also offers a way to avoid marking your properties as virtual, although I would really recommend that you do not use this method (marking classes to avoid lazy loading) as the benefits of lazy loading in most circumstances far outweigh the cost of making your properties virtual.