I am creating new module called "sms" in orchard cms using webmatrix. I create it successfully but when i generate "migrateions.cs", it doesn't generated successfully.
my sms.cs class in Model is given below
using System.Collections.Generic;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Records;
namespace SMSs.Model{
public class smsrecord:ContentPartRecord
{
public virtual int ID{get;set;}
public virtual string Name{get;set;}
public virtual char is_deleted{get;set;}
}
public class smspart:ContentPart<smsrecord>
{
[Required]
public int ID
{
get{return ID=Record.ID;}
set{Record.ID=value;}
}
public string Name
{
get{return Name=Record.Name;}
set{Record.Name=value;}
}
public char is_deleted
{
get{return is_deleted=Record.is_deleted;}
set{Record.is_deleted=value;}
}
}
and the generated Migrations.cs class is as follow
using System;
using System.Collections.Generic;
using System.Data;
using Orchard.ContentManagement.Drivers;
using Orchard.ContentManagement.MetaData;
using Orchard.ContentManagement.MetaData.Builders;
using Orchard.Core.Contents.Extensions;
using Orchard.Data.Migration;
namespace sms {
public class Migrations : DataMigrationImpl {
public int Create() {
return 1;
}
}
}
the "migrations.cs" is not generated successfully why?? Please help
Class itself is generated properly, although it lacks code for creating appropriate tables because you didn't adhere to naming conventions for your record class.
Data migration code generation requires you to follow several conventions in order for it to work properly. I.e.:
Namespace of a record must end with .Models or .Records
There has to exist a public property named Id
All properties have to be virtual (required by NHibernate anyway)
Class cannot be sealed
Class cannot be abstract
Class has to implement IContent or be a subclass of ContentPartRecord
In your case, the namespace (should end with .Models) and incorrect casing of ID (should be Id) are the culprits.
Related
I'm following on some tutorial which creates TodoList and uses multiple layer structure to handle different business logic. When I copy code from the book it shows me an error when I fire dotnet run command in windows cmd. The error I get is displayed bellow so I can specify where lies the problem but don't know how to fix this. What can I do to make this work ? I'm using dotnet 3.0.100 version.
Services\FakeTodoItemService.cs(21,17): error CS0117: 'FakeTodoItemService' does
not contain a definition for 'Title' [C:\dotnetproject\AspNetCoreTodo\AspNetCor
eTodo\AspNetCoreTodo.csproj]Services\FakeTodoItemService.cs(22,17): error CS0117: 'FakeTodoItemService' doesn not contain a definition for 'DueAt' [C:\dotnetproject\AspNetCoreTodo\AspNetCor
eTodo\AspNetCoreTodo.csproj]
And here is a code which I think may be responsible for this error. Basically I have a service that implements interface which uses a model.
FakeTodoItemService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AspNetCoreTodo.Data;
using AspNetCoreTodo.Models;
namespace AspNetCoreTodo.Services
{
public class FakeTodoItemService : ITodoItemService
{
public Task<TodoItem[]> GetIncompleteItemsAsync()
{
var item1 = new TodoItem
{
Title = "Learn ASP.NET Core",
DueAt = DateTimeOffset.Now.AddDays(1)
};
var item2 = new FakeTodoItemService
{
Title = "Build awesome apps",
DueAt = DateTimeOffset.Now.AddDays(2)
};
return Task.FromResult(new[] {item1, item2});
}
}
}
TodoItem.cs
using System;
using System.ComponentModel.DataAnnotations;
namespace AspNetCoreTodo.Models
{
public class TodoItem
{
public Guid Id {get; set;}
public bool IsDone {get; set;}
[Required]
public string Title {get; set;}
public DateTimeOffset? DueAt {get; set;}
}
}
ITodoItemService.cs
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using AspNetCoreTodo.Models;
namespace AspNetCoreTodo.Services
{
public interface ITodoItemService
{
Task<TodoItem[]> GetIncompleteItemsAsync();
}
}
In FakeTodoItemService.GetIncompleteItemsAsync you have this line var item2 = new FakeTodoItemService. FakeTodoItemService should be TodoItem.
I try to implement Metadatatype, in order to seperate Validation attributes from my Acquisitiecode class, into the AcquisitiecodeAnnotations class.
Now when I add attributes (like Required, StringLength and so on) to the Acquisitiecode class, validation works as expected. When I move these attributes to the AcquisitiecodeAnnotations class and bind this class using the MetadataType attribute, I does not work.
Please find the code examples below (I've stripped them down for readability). Also, the project is an ASP.NET Core 3.0 web application. All code, including the examples are also running in.NET Core 3.0 projects.
Snippet 1:
using System;
using System.ComponentModel.DataAnnotations;
namespace Shared.Entities
{
[MetadataType(typeof(AcquisitiecodeAnnotations))]
public partial class Acquisitiecode
{ }
public partial class AcquisitiecodeAnnotations
{
[StringLength(4, ErrorMessage = "The value cannot exceed 4 characters. ")]
public string Acquisitiecode1 { get; set; }
}
}
Snippet 2:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Shared.Entities
{
public partial class Acquisitiecode
{
public Acquisitiecode()
{
Lidmaatschap = new HashSet<Lidmaatschap>();
}
public string Acquisitiecode1 { get; set; }
public virtual Lid Lid { get; set; }
public virtual ICollection<Lidmaatschap> Lidmaatschap { get; set; }
}
}
As of October 2020 the current version of Blazor does not support Metadatatype.
For more information please read this issue.
First time here, never had the need to ask for anything due it was always easy to find the answer in other questions made.
The problem i'm facing:
I've just added the ServiceLayer which is going to publish services correspondant to BusinesLogicLayer.
So this is my code:
using Shared.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
namespace ServiceLayer
{
[ServiceContract]
public interface IServiceEmployees
{
[OperationContract]
void AddEmployee(Employee emp);
[OperationContract]
void DeleteEmployee(int id);
[OperationContract]
void UpdateEmployee(Employee emp);
[OperationContract]
List<Employee> GetAllEmployees();
[OperationContract]
Employee GetEmployee(int id);
[OperationContract]
double CalcPartTimeEmployeeSalary(int idEmployee, int hours);
}
}
Next file:
using BusinessLogicLayer;
using Shared.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ServiceLayer
{
public class ServiceEmployees : IServiceEmployees
{
private static IBLEmployees blHandler;
public ServiceEmployees()
{
blHandler = Program.blHandler;
}
public void AddEmployee(Employee emp)
{
blHandler.AddEmployee(emp);
}
public void DeleteEmployee(int id)
{
blHandler.DeleteEmployee(id);
}
public void UpdateEmployee(Employee emp)
{
blHandler.UpdateEmployee(emp);
}
public List<Employee> GetAllEmployees()
{
return blHandler.GetAllEmployees();
}
public Employee GetEmployee(int id)
{
return blHandler.GetEmployee(id);
}
public double CalcPartTimeEmployeeSalary(int idEmployee, int hours)
{
return blHandler.CalcPartTimeEmployeeSalary(idEmployee, hours);
}
}
}
Next file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace Shared.Entities
{
[DataContract]
[KnownType(typeof(FullTimeEmployee))]
[KnownType(typeof(PartTimeEmployee))]
public abstract class Employee
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public DateTime StartDate { get; set; }
}
}
Next Files:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace Shared.Entities
{
[DataContract]
public class FullTimeEmployee : Employee
{
[DataMember]
public int Salary { get; set; }
}
}
Last File:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace Shared.Entities
{
[DataContract]
public class PartTimeEmployee : Employee
{
[DataMember]
public double HourlyRate { get; set; }
}
}
Allright, those are the ones i need to get published in a wsdl to consume later instead of accessing in PresentationLayer to BusinessLayer and DataLayer.
I've managed to get the published those OperationContracts without problems, and
when i add the url as an service reference on the PresentationLayerWinForm , i get the following.
wsdl description
I need to see the Employee.cs, PartTimeEmployee, FullTimeEmployee clases as well in that description but i dont get them although they are defined in the wsdl.
wsdl_2
What could possibly went wrong ?
Ive cleaned my proyect, rebuiled it several times and i still get the same thing, and i need those clases te get published so i errase the reference to shared.entities from PresentationLayerWinForm
Thanks 4 helping,
Problem Solved;
The issue was that my server-side DataContract class is named the same as a class i'm using local to the client of the web service, so Visual Studio re-uses types by default. Right-click on the Service Reference, Click on Configure and turn off Type re-use.
Thanks Anyway.
I've put together an MVC application using a repository pattern with Entity Framework and everything is going smoothly - but I've run into a stopping block and I'm not sure how to proceed.
I have a few dozen databases with the same schema, and I want to be able to choose one or many at runtime. For example, let's say I start with a database of users (not made yet). That user has connection string information associated with them (possibly more than one). Once the user has "logged in", I want the Enumerables I feed to my Views to contain matching data from all of the databases that user has access to.
Here's an example of what I have right now:
Entity:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations.Schema;
namespace Dashboard.Domain.Entities
{
public class Flight
{
public Guid Id { get; set; }
public string CarrierCode { get; set; }
public string FlightNo { get; set; }
public string MarketingCarrierCode { get; set; }
public string MarketingFlightNo { get; set; }
public string Type { get; set; }
public string TailNo { get; set; }
public string OriginIATA { get; set; }
...
}
}
DB Context:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
using Dashboard.Domain.Entities;
namespace Dashboard.Domain.Concrete
{
public class EFDbContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Passenger>().ToTable("PAX");
}
public DbSet<Flight> Flights { get; set; }
public DbSet<Passenger> PAX { get; set; }
public DbSet<Airport> Airports { get; set; }
}
}
Flight repository interface:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dashboard.Domain.Entities;
namespace Dashboard.Domain.Abstract
{
public interface IFlightRepository
{
IQueryable<Flight> Flights { get; }
}
}
EF Flight Repository:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dashboard.Domain.Abstract;
using Dashboard.Domain.Entities;
namespace Dashboard.Domain.Concrete
{
public class EFFlightRepository : IFlightRepository
{
private EFDbContext context = new EFDbContext();
public IQueryable<Flight> Flights
{
get { return context.Flights; }
}
}
}
Controller:
public class FlightController : Controller
{
private IFlightRepository fRepository;
private IPaxRepository pRepository;
private IAirportRepository aRepository;
public int PageSize = 10;
public FlightController(IFlightRepository flightRepository, IPaxRepository paxRepository, IAirportRepository airportRepository)
{
this.fRepository = flightRepository;
this.pRepository = paxRepository;
this.aRepository = airportRepository;
}
public ViewResult List(byte status = 1, int page = 1)
{ ...
I want those repositories to contain all of the data from all of the connection strings specified, but I have no idea where to start. EF is getting my connection string from the web.config, but I need to be able to set it dynamically somehow and I need to put more than one database's data into the repository.
Is this possible? I should mention that the site is READ ONLY, so I won't need to write changes back to the DBs.
UPDATE:
I've changed the code so I can pass a connection string to the constructor of my EF Repository, but when I try to merge the IQueryables from two different contexts, as below:
public class EFFlightRepository : IFlightRepository
{
private EFDbContext context1 = new EFDbContext(connectionstring1);
private EFDbContext context2 = new EFDbContext(connectionstring2);
private IQueryable<Flight> context;
public EFFlightRepository()
{
context = (IQueryable<Flight>)context1.Flights.Union(context2.Flights);
}
public IQueryable<Flight> Flights
{
get { return context;}
}
}
I get this exception:
The specified LINQ expression contains references to queries that are
associated with different contexts.
How can I combine them so I can run my LINQ queries just like it's ONE set of data?
It is difficult to come up with a detailed solution because it really depends on your software design choices, but I think a possible solution consists of the following things:
1) A method / class that creates a collection of DbContext objects using the DbContext constructor with connection string or connection string name (is the same constructor) as Willian Werlang mentioned:
new DbContext("DB1");
2) Your repositories should be able to accept the list of DbContext's rather than a single one. It could e.g. be injected with the constructor of it.
3) The retrieval methods should iterate over the repositories and load (eager load when detaching) the relevant objects.
4) The retrieved objects could be detached from their DbContext using the following code:
dbContext.Entry(entity).State = EntityState.Detached;
This isn't required but might be a consideration since you would return a mix of different data sources.
5) The retrieved/detached objects should be added to a returned List<> or you could yield return the results one by one with IEnumerable<> is return type.
Returning an IQueryable isn't possible in this case but an IEnumerable will do as result.
An example of a simple retrieval method for a flight repository could be something like:
public IEnumerable<Flight> GetFlights() {
// dbContexts is an IEnumerable<DbContext> that was injected in the constructor
foreach (var ctx in dbContexts) {
foreach (var flight in ctx.Flights) {
yield return flight;
}
}
}
You can set multiples databases on your web.config, but with different names, so your DbContext's can receive the name of the database you want as parameter, like:
new DbContext("DB1");
This way you can choose from which database you'll get the data but I don't think you can get data from multiples bases at the same time with only onde dbContext;
My solution was to change my Repository classes to take a connection string parameter, like this:
namespace Dashboard.Domain.Concrete
{
public class EFFlightRepository : IFlightRepository
{
private EFDbContext context;
public IQueryable<Flight> Flights
{
get { return context.Flights;}
}
public EFFlightRepository(string connectionString)
{
context = new EFDbContext(connectionString);
}
}
}
Then create a factory class (using Ninject.Extensions.Factory) to pass the parameter when the repository is being created (How to pass parameters down the dependency chain using Ninject):
namespace Dashboard.Domain.Factories
{
public interface IFlightRepoFactory
{
IFlightRepository CreateRepo(string connectionString);
}
}
I have another Factory class that produces a list of Repositories based on a list of strings (connection strings to feed to the individual repository classes).
namespace Dashboard.Domain.Factories
{
public interface IRepoCollectionFactory
{
IRepositoryCollection CreateCollection(List<string> connectionStrings);
}
}
Then, in my controller class, I iterate through the Collection generated by the Collection Factory, running whatever query needs to be run on each set of repositories, and combine the results.
This ultimately gives me a list that contains all of the data from each query on each repository.
public FlightController(IRepoCollectionFactory repoCollectionFactory)
{
this.repoCollectionFactory = repoCollectionFactory;
this.collection = repoCollectionFactory.CreateCollection(new List<string> {
// each connection string for each database here
});
}
Bindings in Ninject class:
private void AddBindings()
{
ninjectKernel.Bind<IFlightRepoFactory>().ToFactory();
ninjectKernel.Bind<IAirportRepoFactory>().ToFactory();
ninjectKernel.Bind<IPaxRepoFactory>().ToFactory();
ninjectKernel.Bind<IRepoFactory>().ToFactory();
ninjectKernel.Bind<IRepoCollectionFactory>().ToFactory();
ninjectKernel.Bind<IRepositories>().To<EFRepositories>();
ninjectKernel.Bind<IRepositoryCollection>().To<EFRepositoryCollection>();
ninjectKernel.Bind<IFlightRepository>().To<EFFlightRepository>();
ninjectKernel.Bind<IPaxRepository>().To<EFPaxRepository>();
ninjectKernel.Bind<IAirportRepository>().To<EFAirportRepository>();
}
I have created Enum class of LeaveReason in data access layer having values sick leave,planned leave or other reason now i want to call this enum class to my custom type layer but how to call it ???
please help as i am new in c#...
here is my code looks like.....
In Data Access layer :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sherserve.DataAccessLayer
{
public enum LeaveReason
{
Sick,
Planned,
Other
}
}
In Data Custom Type layer :
Now i want to access enum class which i created in data access layer in custom type layer.
You can see i have added reference of data access layer but it is showing error..
please correct this and tell me how i can call enum class in custom type layer.
using System;
using System.Collections.Generic;
using System.Text;
using Sherserve.DataAccessLayer;
namespace Sherserve.CustomTypeLayer
{
public class EmployeeLeave
{
public LeaveReason LeaveType { get; set; }
public int EmployeeId { get; set; }
public DateTime DateFrom { get; set; }
public DateTime DateTo { get; set; }
public string Reason { get; set; }
}
}
my problem is that i am un able to call enum class from data access to custom type and also i am unable to add reference of data access class to custom type...
please guide me properly..
thanks
You need to add a reference to the Sherserve.DataAccessLayer in the Sherserve.CustomTypeLayer. Typically the Sherserve.CustomTypeLayer would be a class library project that its output is a .dll file that you add to the other dataaccess layer from references -> add reference.