Servicestack OrmLite deleting many to many - servicestack

Let's say I have a ListingEvent class and a UserAccount class.
A ListingEvent can have many UsersAttending and a UserAccount can attend many ListingEvents.
The classes look like:
public class UserAccount
{
[AutoIncrement]
[PrimaryKey]
public int Id {
get ;
set;
}
public string Name {
get ;
set;
}
public UserAccount()
{
ListingEventsAttending = new List<UserAccountListingEvent> ();
}
[Reference]
public List<UserAccountListingEvent> ListingEventsAttending {
get;
set;
}
}
public class UserAccountListingEvent{
[AutoIncrement]
[PrimaryKey]
public int Id {
get;
set;
}
public Model.AttendingStatus Status { get; set; }
[References(typeof(UserAccount))]
public int UserAccountId {
get;
set;
}
[References(typeof(ListingEvent))]
public int ListingEventId {
get;
set;
}
}
public class ListingEvent
{
public ListingEvent()
{
UsersAttending = new List<UserAccountListingEvent>();
}
[AutoIncrement]
[PrimaryKey]
public int Id {
get ;
set;
}
public string Name { get; set; }
[Reference]
public List<UserAccountListingEvent> UsersAttending { get; set; }
public void RemoveUserAttending(UserAccount user)
{
if (user == null)
{
return;
}
UsersAttending.RemoveAll(u => u.UserAccountId == user.Id);
}
}
And I get a ListingEvent that has my UserAccount attending with:
var listingEvent = db.LoadSingleById<Model.ListingEvent> (request.Id);
And I can see that the user with the correct Id is attending so call RemoveUserAttending to remove the user. I can now see the user is not attending so I call:
db.Save (listingEvent, references: true);
But - now when I go to fetch that ListingEvent again the user is back to attending.
So my question is:
should the above work as expected?
if not - how should I be doing this?

db.Save() only INSERT or UPDATE entities i.e. it doesn't DELETE them.
To delete, retrieve the entities or entity Ids you want to delete and use OrmLite's db.Delete* API's explicitly, e.g. something like:
var removeUsersAttendingIds = listingEvent.UsersAttending
.Where(u => u.UserAccountId == user.Id)
.Select(u => u.Id);
db.DeleteByIds<UserAccountListingEvent>(removeUsersAttendingIds);

Related

AutoMapper One-To-Many Filter and ProjectTo

I have the below two Entities (one-to-many)
public class ApplicationCode
{
public Guid ApplicationId { get; set; }
public string? ApplicationAcrynom { get; set; }
public int ApplicationIndex { get; set; }
public IList<ApplicationCodeTranslation> ApplicationCodeTranslations { get; private set; } = new List<ApplicationCodeTranslation>();
}
public class ApplicationCodeTranslation
{
public Guid ApplicationCodeTranslationId { get; set; }
public Guid ApplicationId { get; set; }
public Guid LanguageId { get; set; }
public string? ApplicationDescription { get; set; }
public ApplicationCode ApplicationCode { get; set; } = null!;
}
The goal is to populate the below Dto where I need to filter one language from the child list (IList ApplicationCodeTranslations) in the ApplicationCode entity to get the description value
public class ApplicationCodeDto : IMapFrom<ApplicationCode>
{
public Guid ApplicationId { get; set; }
public string? ApplicationAcrynom { get; set; }
public string? ApplicationDescription { get; set; }
public void Mapping(Profile profile)
{
profile.CreateMap<ApplicationCode, ApplicationCodeDto>();
profile.CreateMap<ApplicationCodeTranslation, ApplicationCodeDto>();
}
}
I tried below, but it does not give the intended result.
It omits the ApplicationDescription (gives null), the whole .Include line is not translated to SQL at all.
var test1 = await _context.ApplicationCodes
.Include(e => e.ApplicationCodeTranslations.Where(l => l.LanguageId == _languageId))
.ProjectTo<ApplicationCodeDto>(_mapper.ConfigurationProvider)
.ToListAsync();
The other option I tried is
var test2 = await _context.ApplicationCodes
.SelectMany(e => e.ApplicationCodeTranslations)
.Where(l => l.LanguageId == _languageId)
.ProjectTo<ApplicationCodeDto>(_mapper.ConfigurationProvider)
.ToListAsync();
Which omits the properties of the CodeApplication and brings only the child list properties, as SelectMany only brings back the props of the child.
The only way I managed to make it work is below:
var test3 = await _context.ApplicationCodes
.SelectMany(e => e.ApplicationCodeTranslations.Where(l => l.LanguageId == _languageId),
(a,t) => new ApplicationCodeDto{
ApplicationId = a.ApplicationId,
ApplicationAcrynom = a.ApplicationAcrynom,
ApplicationDescription = t.ApplicationDescription,
})
.ToListAsync();
How can AutoMapper (v.11) help in this scenario to avoid mapping the DTO props manually?
Does ProjectTo work here?

Autquery not including nested result when using a response DTO

Let's say you have these models:
public class Blog
{
[PrimaryKey]
[AutoIncrement]
public int Id { get; set; }
public string Url { get; set; }
public string PrivateField { get; set; }
[Reference]
public List<BlogToBlogCategory> BlogToBlogCategories { get; set; }
}
public class BlogResponse
{
public int Id { get; set; }
public string Url { get; set; }
public List<BlogToBlogCategory> BlogToBlogCategories { get; set; }
}
And this request:
public class BlogsLookUpRequest : QueryDb<Blog, BlogResponse>
{
}
The return value will have BlogToBlogCategories as null, but this request:
public class BlogsLookUpRequest : QueryDb<Blog>
{
}
Will have BlogToBlogCategories populated. I can manually create the query response like so with custom implementation:
var q = _autoQuery.CreateQuery(request, Request.GetRequestParams(), base.Request);
var results = _autoQuery.Execute(request,q, base.Request);
return new QueryResponse<ResponseBlog>()
{
Results = results.Results.ConvertTo<List<ResponseBlog>>(),
Offset = request.Skip,
Total = results.Total
};
Then it will have the nested results. If I decorate the collection with [Reference] then it is trying to find foreign key on non-existant BlogResponse table.
Why are referenced results removed when specifying a return model with AutoQuery? Is there a way to mark it up so it works?
The POCO Reference Types is used to populate Data Models not adhoc Response DTOs.
In this case it's trying to resolve references on a non-existent table, you can specify which table the DTO maps to with [Alias] attribute, e.g:
[Alias(nameof(Blog))]
public class BlogResponse
{
public int Id { get; set; }
public string Url { get; set; }
public List<BlogToBlogCategory> BlogToBlogCategories { get; set; }
}

How to fix 'model code generator' in asp.net mvc 5

I modelling a simple library management system that able to register user and the user can issue a book.
I want the asp.net IdentityUser to create one -to many relationShip with BookIssue Custom table. because I am new to asp.net mvc 5, I can not fix the problem please help me.
public class ApplicationUser : IdentityUser
{
public virtual ICollection<BookIssue> BookIssues { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public DbSet<Book> Books { get; set; }
public DbSet<BookIssue> BookIssues { get; set; }
public DbSet<Catagory> Catagories { get; set; }
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
modelBuilder.Entity<BookIssue>()
.HasRequired(n => n.ApplicationUser)
.WithMany(a => a.BookIssues)
.HasForeignKey(n => n.ApplicationUserId)
.WillCascadeOnDelete(false);
}
}
}
BookIssue Model:
public int BookIssueId { get; set; }
public int BookId { get; set; }
public int ApplicationUserId { get; set; }
public string Email { get; set; }
public DateTime FromDate { get; set; }
public DateTime ToDate { get; set; }
public virtual Book Book { get; set; }
public virtual ApplicationUser ApplicationUser { get; set;
The generated error:
There was an error running the selected code generator. 'Unable to
retrieve metadata for Librart.Models.BookIssuee'.One or more
validation errors were detected during model generation:
Library.Models.IdentityUserLogin: EntityType 'IdentityUserRole' has no
key defined.Define the key for this EntityType.
Library.Models.IdentityUserRole: EntityType 'IdentityUserLogin' has no
key defined.Define the key for this EntityType.
And many other errors are generated.

Automapper Object with inside list of object to primitive mapping

I'm trying to create map for automapper to let me map those entity
Entities
public class Entity
{
...
public List<NavigationEntity> Navs { get; set; }
}
public class NavigationEntity
{
public int Id { get; set; }
}
DTO that need to be create with entities
public class EntityDto
{
...
public List<int> NavIds { get; set; }
}
This doesnt seem's to do the job! What could do the job ?
CreateMap<Entity, EntityDto>().ReverseMap();
CreateMap<NavigationEntity, int>().ConstructUsing(x => x.Id);
EDIT
Tried to add
CreateMap< List < SystemsTags >, List< int >>();
but still it doesnt map
First of all, you should rename public List<NavigationEntity> Navs { get; set; } and public List<int> NavIds { get; set; } to the same name. If it is still not working try to also change ConstructUsing to ConvertUsing. And if you need the reverseMap of Entity to EntityDTO you should also add
CreateMap<int, NavigationEntity>().ConvertUsing(x => new NavigationEntity { Id = x });
final code
public class Entity
{
...
public List<NavigationEntity> Navs { get; set; }
}
public class NavigationEntity
{
public int Id { get; set; }
}
public class EntityDto
{
...
public List<int> Navs { get; set; }
}
...
CreateMap<Entity, EntityDto>().ReverseMap();
CreateMap<NavigationEntity, int>().ConvertUsing(x => x.Id);
CreateMap<int, NavigationEntity>().ConvertUsing(x => new NavigationEntity { Id = x });

Deserializing oData to a sane object with ServiceStack

So here's what I'm getting back from the oData service...
{
"odata.metadata":"http://server.ca/Mediasite/Api/v1/$metadata#UserProfiles",
"value":[
{
"odata.id":"http://server.ca/Mediasite/Api/v1/UserProfiles('111111111111111')",
"QuotaPolicy#odata.navigationLinkUrl":"http://server.ca/Mediasite/Api/v1/UserProfiles('111111111111111')/QuotaPolicy",
"#SetQuotaPolicyFromLevel":{
"target":"http://server.ca/Mediasite/Api/v1/UserProfiles('111111111111111')/SetQuotaPolicyFromLevel"
},
"Id":"111111111111111",
"UserName":"testuser",
"DisplayName":"testuser Large",
"Email":"testuser#testuser.ca",
"Activated":true,
"HomeFolderId":"312dcf4890df4b129e248a0c9a57869714",
"ModeratorEmail":"testuser#testuserlarge.ca",
"ModeratorEmailOptOut":false,
"DisablePresentationContentCompleteEmails":false,
"DisablePresentationContentFailedEmails":false,
"DisablePresentationChangeOwnerEmails":false,
"TimeZone":26,
"PresenterFirstName":null,
"PresenterMiddleName":null,
"PresenterLastName":null,
"PresenterEmail":null,
"PresenterPrefix":null,
"PresenterSuffix":null,
"PresenterAdditionalInfo":null,
"PresenterBio":null,
"TrustDirectoryEntry":null
}
]
}
I want to deserialize this into a simple class, like just the important stuff (Id, Username, etc...to the end).
I have my class create, but for the life of me I can't figureout how to throw away all the wrapper objects oData puts around this thing.
Can anyone shed some light?
You can use JsonObject do dynamically traverse the JSON, e.g:
var users = JsonObject.Parse(json).ArrayObjects("value")
.Map(x => new User
{
Id = x.Get<long>("Id"),
UserName = x["UserName"],
DisplayName = x["DisplayName"],
Email = x["Email"],
Activated = x.Get<bool>("Activated"),
});
users.PrintDump();
Or deserialize it into a model that matches the shape of the JSON, e.g:
public class ODataUser
{
public List<User> Value { get; set; }
}
public class User
{
public long Id { get; set; }
public string UserName { get; set; }
public string DisplayName { get; set; }
public string Email { get; set; }
public bool Activated { get; set; }
public string HomeFolderId { get; set; }
public string ModeratorEmail { get; set; }
public bool ModeratorEmailOptOut { get; set; }
public bool DisablePresentationContentCompleteEmails { get; set; }
public bool DisablePresentationContentFailedEmails { get; set; }
public bool DisablePresentationChangeOwnerEmails { get; set; }
public int TimeZone { get; set; }
}
var odata = json.FromJson<ODataUser>();
var user = odata.Value[0];

Resources