MVC Check value Select insert using EntityFramework :
Controller :
var skill = Skill.GetOrCreate(Db, skillData.skill.name);
TGDb.Save<UserSkill>(new UserSkill
{
user_id = userid,
skill_id = skill.id,
priority = 10,
});
skill Models :
using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel.DataAnnotations.Schema;
using API.Database;
namespace API.Models
{
public class Skill : IDataModel
{
public long id { get; set; }
public string name { get; set; }
public static Skill GetOrCreate(DbContext Db, string name)
{
//Select The Value
var query = from s in Db.skills -->DBContext
where s.name == name
select s;
var skill = query.SingleOrDefault();
if (skill == null)
{
var newSkill=new Skill();
newSkill.name = name;
//Insert The Value
skill = TGDb.Save<Skill>(newSkill);
}
return skill;
}
}
}
DB Context :
Add -->
public DbSet<Skill> skills { get; set; }
No comments:
Post a Comment