Wcf ria services - custom objects with EF entities - can't compile - asp.net

I have custom entity (not from entity model), which have a property, wich return collection of EF entities (from entity model):
[DataContract]
public class MyEntity
{
[DataMember]
public List<Role> Roles { get; set; }
}
The 'Role' and 'RolePermission' entities are generated by EF4 from DB.
RolePermission has FOREGIN_KEY to Role, and EF4 was generated association between Role and RolePermission:
Role.RolePermissions --navigate property
RolePermission.Role --navigate property
Also, I have DomainService:
[EnableClientAccess()]
public class MyEntityService : DomainService
{
public List<MyEntity> GetMyEntities()
{
...
myEntityInstance.Roles = <GetRoles>
...
return <collection of MyEntities with Roles>
}
}
When I try to compile this, I get error:
Entity 'UserManager.Web.RolePermission' has a property 'RoleReference' with an unsupported type
When I put [Include] attribute to MyEntity.Roles property, I get the same error and this error:
Property 'Roles' of complex type 'MyEntity' is invalid. Complex types cannot have include members.
when I removed reference from RolePermission to Role (RolePermission.Role navigate property) by hands (from entity model), I get only this error in compile time:
The Entity 'Role' in DomainService 'RolesService' does not have a key defined. Entity types exposed by DomainService operations must have at least one public property marked with the KeyAttribute.
How can I resolve this situation? How can I return my custom object (MyEntity) with filled Roles property from MyEntityService?
A added [key] attr to Role.Metadata, and compile succesfull. But there are no MyEntity.Roles property on the client.

RIA services requires all objects passed back and forth between client to server to have a unique key so it knows which specific object you are modifying.
If you must have your own object as a wrapper for EF objects, just add an id member marked with [key] and maintain that value yourself.
[DataContract]
public class MyEntity
{
[key]
public int Id { get; set; }
[DataMember]
public List<Role> Roles { get; set; }
}
There seems to be something wrong with the design if you need to do that. What is the parent of a group of roles in your application? Why not just query roles?

Related

I have one entity, i need to add property of entity type

**public class Ticket : BaseEntity
{
public TicketType TicketType { get; set; }
}
public class TicketType : AuxiliaryInfoBaseEntity
{
public string Description { get; set; }
}**
In Ticket Entity i need one property of TicketType and type of column should be byte in Ticket.
Resulting table will look like.Table-Ticket:column TicketType(tinyint,not null).
When i trying to migrate, i am getting this exception.
System.InvalidOperationException: 'The property 'Ticket.TicketType' is of type 'TicketType' which is not supported by current database provider. Either change the property CLR type or ignore the property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
Please help me with some soluntion thanks.

No key defined. Define the key for this EntityType when implementing interface that has Id

I want to implement an interface defined in Dev Express IResource in my EF Code First business object.
public class JResource : IResource , IXafEntityObject
{
[Key]
public int IdKey { get; set; }
[NotMapped]
public object Id => IdKey; // since IResource wants this.
// other properties
}
When I run my application to create the database I get an error that I need to define the key for this EntityType.
I think the problem is that EF wants to regard Id as the Key but I have made Id NotMapped since I want it to be an Int and the interface wants it to be an object.
Is there a work around?
It turned out that I was using the wrong reference for the [Key] attribute.
The correct one is
System.ComponentModel.DataAnnotations.KeyAttribute

Ignore column but populate property through stored procedure EF code first

I have ignored a column through fluent API but want to populate that property while executing stored procedure using some logic. But it is not mapping the ignored column property. Please let me know if there is any way to do this in Entity framework code first.
I've faced with the same problem recently. The only solution I found is a class hierarchy:
public class MyEntityBase {
public int Id { get; set; }
}
public class MyEntity: MyEntityBase {
...
}//This class is mapped to DB with a fluent API and does not contain ignored property.
//Also it does not have derivative classes, so EF will not create class inheritance in DB.
public class DerivedEntity: MyEntityBase {
public int IgnoredProperty { get; set; }
}//Use this class while executing stored procedures
P.S. Do not mark class MyEntityBase as ABSTRACT - EF will map this relationship as database inheritance.

EF Code First - Fluent API (WithRequiredDependent and WithRequiredPrincipal)

I have the following class:
public class User
{
public Guid Id { get; set; }
public string Name { get; set; }
public Couple Couple { get; set; }
}
public class Couple
{
public Guid Id { get; set; }
public User Groom { get; set; }
public User Bride { get; set; }
}
Important points:
Bride and Groom properties are required
One-to-one relationship
In the User class, it is Couple required
DbContext in OnModelCreating
modelBuilder.Entity<User>().HasRequired(u => u.Couple).WithRequiredPrincipal();
modelBuilder.Entity<Couple>().HasRequired(u => u.Bride).WithRequiredDependent();
modelBuilder.Entity<Couple>().HasRequired(u => u.Groom).WithRequiredDependent();
But I can not be required!
All fileds are with null in the database!.
How do I get the fields in the database as not null?
If possible using the API Flient.
It should be this :
modelBuilder.Entity<User>().HasRequired(u => u.Couple).WithRequiredDependent();
modelBuilder.Entity<Couple>().HasRequired(u => u.Bride).WithRequiredDependent();
modelBuilder.Entity<Couple>().HasRequired(u => u.Groom).WithRequiredDependent();
How WithRequiredDependent Works : Configures the relationship to be required:required without a navigation property on the other side of the relationship. The entity type being configured will be the dependent and contain a foreign key to the principal. The entity
type that the relationship targets will be the principal in the relationship.
Meaning : Let's consider your first line of code here. It creates a foreign key in the entity being configured (User) making it Dependant and making the other side of the relationship (Couple) Principal
Important : Don't you think the configuration you desire will generate a deadlock? I've not tested the code above, but this configuration seems to be a deadlock to me so i'm not sure if EF would allow you to create it. User must need a Couple, and Couple must need that same user i guess.

How to delete child entities in an InverseProperty relationship using code first entity framework 4.1

I have a model and I am having trouble managing the relationships using entity framework 4.1
Here the model (simplified):
public class UserConfig {
[Key]
[Column("id", TypeName = "bigint")]
public long Id { get; set;}
[InverseProperty("UserConfigId")]
public virtual List<ColumnConfig> ColumnConfigs { get; set; }
}
public class ColumnConfig {
[Key]
[Column("id", TypeName = "bigint")]
public long Id { get; set; }
[Column("user_config_id", TypeName = "bigint")]
public long UserConfigId { get; set; }
[Column("width", TypeName = "int")]
public int Width{ get; set; }
[Column("col_name", TypeName = "varchar")]
public string ColumnName{ get; set; }
}
The model represents a user and a custom view of a table of data within a UI. They resize the columns the way they want and then save their settings. I have a webservice that accepts a list of the columns they want and their respective widths.
The problem I am having is updating the user's ColumnConfigs within my web service. The webservice does not receive the ColumnConfig id's, so my approach has been to try and first delete all the existing ColumnConfigs for the user, and then second create a new set of objects according to the new values passed in.
I can't manage to delete any of the ColumnConfig objects. Here's my code:
public void UpdateUserConfig(UserConfig uc) {
UserConfig origUserConf = ctx.ColumnConfigs.Find(new object[] {uc.Id});
origUserConf.ForEach(uc => ctx.ColumnConfigs.Remove(uc)); // remove old
origUserConf.ColumnConfigs = uc.ColumnConfigs; // add new
ctx.SaveChanges();
}
This isn't working, it gives the error:
System.InvalidOperationException: The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.
at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at System.Data.Entity.DbContext.SaveChanges()
I'm not sure why is thinks there is a null constraint here. I haven't specified any fields as being required.
The easiest way to remove child relationships would be to invoke:
origUserConfig.ColumnConfigs.Clear();
Unfortunately, this wouldn't work for you for two reasons: (1) You have a non-nullable relationship defined between your Parent and Child entity, and (2) even if the relationship was defined as nullable it would orphan the child rather than deleting it.
Read this article (Deleting Foreign Key Relationships in EF4) to get an idea of how EF handles deleting child entities. In your case you fall under case number 1.
As far as the error you're getting change your foreach to use the ForEach method off the List<T> class:
origUserConf.ColumnConfigs.ForEach(col => ctx.ColumnConfigs.Remove(col))

Resources