using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;

namespace BookDemo.QA
{
    public partial class NewQuestion : System.Web.UI.Page
    {
        private BookDemoEntities ctx = new BookDemoEntities();

        protected void Page_Load(object sender, EventArgs e)
        {
            Common.CheckLogin();//验证登陆
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            //从缓存中获取CatalogDropDownList.ascx控件中的ddlCatalogs的客户端Name
            string ddlCatalogsClientName = Page.Cache["CatalogDropDownListClientName"].ToString();
            //获取选择的目录ID
            int catalogId = Convert.ToInt32(Request.Form[ddlCatalogsClientName]);
            string userName = Common.GetUserName();//获取当前登陆用户名

            #region 原始读取数据库方法
            QACatalog catalog = ctx.QACatalog.First(c => c.Id == catalogId);//获取目录实体
            QAUserInfo userInfo = ctx.QAUserInfo.First(u => u.UserName == userName);//获取用户信息实体
            #endregion

            #region 从缓存中读取，此处不可行，因为会QAQuestion实体的QACatalog和QAUserInfo属性从两个不同的ObjectContext获取
            //CatalogCache catalogCache = new CatalogCache();
            //UserInfoCache userInfoCache = new UserInfoCache();
            //QACatalog catalog = catalogCache.Data.First(c => c.Id == catalogId);//获取目录实体
            //QAUserInfo userInfo = userInfoCache.Data.First(u => u.UserName == userName);//获取用户信息实体
            #endregion

            QAQuestion question = new QAQuestion
            {
                Title = txtTitle.Text.Trim(),//标题
                Text = txtText.Text.Trim(),//提问内容
                AdditionText = string.Empty,//附加说明
                PostDatetime = DateTime.Now,//发布时间
                Mark = 0,//悬赏分数
                State = 0,//0表示未解决,1表示已解决,2表示已关闭

                QACatalog = catalog,//所属目录
                QAUserInfo = userInfo//用户信息
            };

            QAConfig config = ctx.QAConfig.FirstOrDefault();//获取全局设置
            config.Unsolve++;

            ctx.SaveChanges();//保存所有数据库修改

            Response.Redirect("~/Default.aspx");//返回首页
        }
    }
}
