I'm trying to extend the RolePermissionSetting class with additional properties the thing is that this class is declared in abstract AbpRoleBase class, which is used across the framework is there a way to accomplish this without generating a different AbpPermissions table in the DB.
Here is the piece of code:
public abstract class AbpRoleBase : FullAuditedEntity<int>, IMayHaveTenant{
..
public virtual ICollection<RolePermissionSetting> Permissions { get; set; }
}
my Role class inherit from AbpRole(ZeroModule) which override AbpRoleBase, I'm afraid that if I replace that class with my own, EF will generate a new table in the model then I'll have two Role Tables.
EF will not generate a new table, but add a Discriminator column, which should be fine.
AbpRole implements, not overrides, AbpRoleBase. You can safely override Permissions property in Role.cs.
Related
I'm new to MVC and the EF. My app is a simple code-first with several POCO classes and a DBContext like this:
public class ExpDefContext : DbContext
{
public DbSet<Experiment> Experiments { get; set; }
public DbSet<Research> Researches { get; set; }
...
The problem: I need to add to my data model an entity-set that its type is built at runtime from user input, meaning I have no idea of its data structure.
I read the non-generic Dbset class is made just for this, so I added to the context:
public DbSet Log { get; set; }
...and created a constructor for the context that accepts the runtime-type and sets the new Dbset:
public ExpDefContext(Type LogRecType)
{
Log = Set(LogRecType);
}
(the type by the way is built using Reflection.Emit).
In the controller I create the type (named LogRec) and pass it to a new DBContext instance. Then I create a LogRec instance and try to Add it to the database:
Type LogRec;
LogRec = LogTypeBuilder.Build(dbExpDef, _experimentID);
var dbLog = new ExpDefContext(LogRec);
var testRec = LogRec.GetConstructor(Type.EmptyTypes).Invoke(Type.EmptyTypes);
dbLog.Log.Add(testRec);
dbLog.SaveChanges();
and I get an exception from the dbLog.Log.Add(testRec):
The entity type LogRec is not part of the model for the current context
What am I doing wrong?
Is there a better way to do this (preferably without diving too deep into the Entity Framework)?
Thanks
I suspect that EF only reflects over the generic DbSet<T> properties in your derived DbContext and ignores any non-generic DbSet properties when the model is created in memory.
However, an alternative approach might be to use the Fluent API in OnModelCreating to add your dynamic type as an entity to the model.
First of all you can add a type to the model only when the model is built in memory for the first time your AppDomain is loaded. (A model is built only once per AppDomain.) If you had a default constructor of the context in addition to the overloaded constructor and had created and used a context instance using this default constructor your model would have been built with only the static types and you can't use the dynamic type as entity anymore as long as the AppDomain lives. It would result in exactly the exception you have.
Another point to consider is the creation of the database schema. If your type is unknown at compile time the database schema is unknown at compile time. If the model changes due to a new type on the next run of your application you will need to update the database schema somehow, either by recreating the database from scratch or by defining a custom database initializer that only deletes the LogRec table and creates a new table according to the new layout of the LogRec type. Or maybe Code-First Migrations might help.
About the possible solution with Fluent API:
Remove the DbSet and add a Type member instead to the context and override OnModelCreating:
public class ExpDefContext : DbContext
{
private readonly Type _logRecType;
public ExpDefContext(Type LogRecType)
{
_logRecType = LogRecType;
}
public DbSet<Experiment> Experiments { get; set; }
public DbSet<Research> Researches { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
var entityMethod = typeof(DbModelBuilder).GetMethod("Entity");
entityMethod.MakeGenericMethod(_logRecType)
.Invoke(modelBuilder, new object[] { });
}
}
DbModelBuilder doesn't have a non-generic Entity method, hence dynamic invocation of the generic Entity<T> method is necessary.
The above code in OnModelCreating is the dynamic counterpart of...
modelBuilder.Entity<LogRec>();
...which would be used with a static LogRec type and that just makes the type as entity known to EF. It is exactly the same as adding a DbSet<LogRec> property to the context class.
You should be able to access the entity set of the dynamic entity by using...
context.Set(LogRecType)
...which will return a non-generic DbSet.
I have no clue if that will work and didn't test it but the idea is from Rowan Miller, member of the EF team, so I have some hope it will.
Is there a different way of setting the [AllowHtml] attribute on a property of a class that is being auto-generated by EntityFramework? I hate changing the autogenerated files because every time I make a change to the model, my changes get lost.
But there is no other obvious way for setting [AllowHtml] for a specific property other than by using the attribute. Is there a non-attribute way of doing it?
You can use the MetadataTypeAttribute to specify attributes for the generated code in an associated (buddy) class. So you put your attributes in a separate class which won't be effected with the code re-generation:
[MetadataType(typeof(YourEntityMetadata))]
public partial class YourEntityClass
{
}
public class YourEntityMetadata
{
[AllowHtml]
public string YourPropertyWithHtml { get; set; }
}
The property names in the Metadata class should match your entity property names.
I am using Spring Security plugin in my grails app. I have extended Springs User class in my own generated Physician class. Now when I run app I am not getting physician table in database instead User class only has all properties defined in Physician Domain. I need to have separate table for Physician.
When I try to find all Users in User table with User.findAll() my output is,
[com.HospitalManagement.User : 1, com.HospitalManagement.User : 2, com.HospitalManagement.User : 3, com.HospitalManagement.User : 4, com.HospitalManagement.User : 5, com.HospitalManagement.User : 6, com.HospitalManagement.User : 7, com.HospitalManagement.User : 8, com.HospitalManagement.User : 9]
but I was expecting username and other physician properties values.
What could the problem be?
Domain Class is:
package com.HospitalManagement
class Physician extends User{
static constraints = {
}
String specilty;
String MobileNo;
String Physician_Address;
String clinicals;
}
By default, GORM uses a table-per-hierarchy model for domain classes with inheritance. All fields in the parent class and all fields in each subclass will be stored in a single table.
If you want to turn off this functionality, you can use the tablePerHierarchy mapping parameter. Setting this parameter to false will put the parent class fields in a common parent table, and put the fields for each subclass in their own table. This can make your queries slightly less efficient because the queries will will have joins, but if the inheritance tree is small, the difference should be negligible. Here's what it would look like with your domain class:
package com.HospitalManagement
class Physician extends User {
static constraints = {
}
String specilty;
String MobileNo;
String Physician_Address;
String clinicals;
static mapping = {
tablePerHierarchy false
}
}
See The grails documentation for more information:
Inheritance Strategies
Inheritance in GORM
If you want each subclass to have it's own table which contains all fields from the parent class and all fields from the subclass, then you can define the parent class as 'abstract' and that should prevent grails from making a separate table for it. Grails should only create tables for concrete domain classes, not abstract domain classes. [Source]
Your user class would look then look something like this:
abstract class User {
String username
String password
//etc...
}
This will build the tables correctly, though I'm not sure what effect it might have on Spring Security. If you see any Spring Security errors after making the User class abstract, I'd fall back to disabling table-per-hierarchy and dealing with the joins.
It sounds like you're trying to display the attributes of an object. Perhaps you just want to override toString() for your Physician class:
package com.HospitalManagement
class Physician extends User{
static constraints = {
}
String specilty;
String MobileNo;
String Physician_Address;
String clinicals;
String toString() {
"specilty: $specilty, MobileNo: $MobileNo, Physician_Address: $Physician_Address, clinicals: $clinicals"
}
}
or something like that, depending on how you want the output to be formatted.
I'm working on an MVC3 application.
I created my POCO classes through the ADO.NET DbContext Generator and
I'm using partial classes to add validation on properties.
Now, when I try to serialize one of my entities I receive this error:
"Cannot serialize member .... of type
'System.Collections.Generic.ICollection`1[....."
I googled this error and I discovered that it's possible to add the tag
[XmlIgnore] to certain properties.
But the point is that I can't put this tag on the properties because they are
created everytime by the generator.
So how I can do this in a simpler way ?
The key is the MetadataTypeAttribute. You can add this to your partial class which implements the additional properties and your validation logic. Then create a meta data class with a property of the same name of your generated class, and apply the attribute you need.
[MetadataType(typeof(MyPOCOMetaData))]
public partial class MyPOCO
{
// your partial validation code and properties
}
public class MyPOCOMetaData
{
[XmlIgnore]
public string GenerateProperyName { get; set; }
}
Castle Validator uses attributes to specify validation rules. How can you hook these up with Subsonic's generated classes (or any classes where you can't define the attributes on)? Is there a way to programatically specify validation rules without using the attribute method?
I think the best way to do that is using MetadataType.
It's a DataAnnotations that let's your class have like a pair or something like that. I don't know how to explain it better so, let's for the samples:
You first need to add this directive to your code:
using System.ComponentModel.DataAnnotations;
Them you should create the partial class of you generated class with an attribute specifying that this class has an MetadataType:
[MetadataType(typeof(UserMetadata))]
public partial class User
{
}
Then you create your metadata class with your castle validation:
public class UserMetadata
{
[ValidateNonEmpty]
[ValidateLength(6, 24)]
public string Username { get; set; }
[ValidateNonEmpty]
[ValidateLength(6, 100)]
[ValidateEmail]
public string Email { get; set; }
[ValidateNonEmpty]
[ValidateLength(6, 24)]
public string Password { get; set; }
}
There are a few ways to do this - attributes is the lowest friction option, but obviously doesn't deal well with generated code or validation of multiple properties better expressed in code.
Take a look at the following link for some indications on how to do this blog post: Castle Validator Enhancements
If you have a look at the castle source code these are some good starting points:
IValidationContributor interface
DefaultValidationPerformer class